text
stringlengths
10
2.61M
# encoding: UTF-8 #não é necessários nas versões 2.0 e acima #Comandos de saida de dados #Pula uma linha puts "Olá mundo" #Imprime e não pula linha print "Olá mundo" #Chama o método inspect do elemento p "Olá mundo" #Comentário de uma só linha =begin Comentário multi linha =end #Variáve...
class InventoriesController < ApplicationController before_action :find_category, only: [:show, :edit, :update, :destroy] def index @inventories = Inventory.all end def show @items = @inventory.items.all end def new @inventory = Inventory.new end def create @inventory = Inventory.new(inventory_param...
# frozen_string_literal: true require 'bindata' module JavaSerialization class NullReference < BinData::Primitive def get "TC_NULL" end def set(v) end end end
class Players def initialize(name, lives = 3) @name = name @lives = lives end def still_alive? @lives.positive? end attr_accessor :name, :lives end
# frozen_string_literal: true FactoryBot.define do factory :location_event, class: 'Location::Event' do start_at { '2019-09-23 12:01:19' } end_at { '2019-09-23 12:01:19' } name { 'MyString' } snippet { 'MyString' } content { 'MyText' } address { 'MyString' } elvanto_form_id { 'MyString' }...
class Tracktype < ActiveRecord::Base attr_accessible :code, :name has_many :tracks, :foreign_key => "tracktype_code", :primary_key =>"code" end
class ChangeConversationsSenderAttribute < ActiveRecord::Migration def up remove_column :conversations, :sender_id add_column :conversations, :sender_id, :integer end def down end end
class LoginPage < BasePage element :choose_network, :xpath, ".//div[@class='network-name']" # elements because it is clickable on multiple same name items. elements :network_name, :xpath, "//li[@class='dropdown-menu-item']" element :btn_accept, ...
class Film < ActiveRecord::Base validates :name, :year, :image, :genre, :director, :actors, :content, :presence => true has_many :comments, :dependent => :destroy end
# Showing all orders via main menu get '/orders' do @orders = Order.order("created_at DESC") @items = LineItem.where(:order_id => @orders.id) @venue = Venue.where(:venue_id => @orders.venue_id) @customer = Customer.where(:customer_id => @orders.customer_id) erb :"orders/index", :layout => (request.xhr? ? fals...
# perform_again.rb loop do puts "Do you want to do that again?" answer = gets.chomp if answer != 'Y' break end end # Side note: Another construct in Ruby that supports `do/while` loops # although, this is not recommended by Matz: begin puts "Do you want to do that again?" answer = gets.chomp end whil...
Given 'we have the client tools setup' do step 'the libra client tools' step 'the client tools should be setup if needed' end Given 'we have an existing domain' do step 'we have the client tools setup' step 'a new domain is needed and created' begin step 'the key "key1" is shown' step 'the output inc...
class Board < ApplicationRecord has_many :cells accepts_nested_attributes_for :cells def cells_attributes=(cells_attributes) cells_attributes.each do |cell_attributes| cell = Cell.create(cell_attributes) self.cells << cell end end end
class RecipesController < ApplicationController before_action :set_recipe, only: [:show, :edit, :update, :destroy] def index # @recipes = Recipe.all @recipes = Recipe.search params[:search] @recipes = @recipes.order(created_at: :desc).paginate(page: params[:page], per_page: 5) @categories = Categor...
class RemoveUnwantedTreatmentFields < ActiveRecord::Migration def change remove_column :treatments, :substance remove_column :treatments, :concentration end end
class Article < ActiveRecord::Base #associations belongs_to :headline belongs_to :user scope :last_article, -> { where('created_at desc') } #validations validates :content, length: { minimum: 1100, maximum: 2200 } #acts_as_votable acts_as_votable def next(key = :id) self.class.where("#{key} > ?", send(...
class User < ApplicationRecord has_many :ratings mount_uploader :avatar, AvatarUploader devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable has_many :active_relationships, class_name: "Relationship", foreign_key: "follower_id", dependent: :destroy ...
module Constant # variable harus capital NILAI =100,'dan bernilai string' # error nilai = 100 module A NILAI = 200,'dan bernilai bernilai string' end end puts Constant::NILAI puts Constant::A::NILAI
require 'pry' class Backer attr_accessor :name @@all = [] def initialize(name) @name = name @@all << self end def self.all @@all end def back_project(project) ProjectBacker.new(project, self) end def backed_projects ProjectBacker.all.select {...
$:.unshift(File.dirname(__FILE__)+"/lib") require 'subcommand' require 'rim/file_logger' require 'rim/command/sync' require 'rim/command/upload' require 'rim/command/status' require 'rim/command/info' require 'rim/git' require 'rim/rim_exception' require 'rim/version' require 'tmpdir' include Subcommands # -C option ...
class ContractsController < ApplicationController before_action :commercial def index @grid_contracts = ContractsGrid.new(params[:contracts_grid]) do |scope| scope.page(params[:page]) end end def new @contract = Contract.new @active = 1 build_contracts end def edit @contract = Contract.find pa...
#!/usr/bin/env ruby -ws # Update the flog scores for a specific set of gems. $: << 'lib' << '../../ParseTree/dev/lib' $:.unshift File.expand_path("~/Work/svn/rubygems/lib") require 'yaml' require 'flog' require 'gem_updater' $u ||= false $f ||= false $score_file = '../dev/scores.yml' $misc_error = {:total => -...
require 'test_helper' class UsersLoginTest < ActionDispatch::IntegrationTest # test "the truth" do # assert true # end def setup @user = users( :michael ) # get michael user from fixtures; users corresponds to the fixture filename users.yml end test "login with invalid information" do get log...
json.array!(@insurances) do |insurance| json.extract! insurance, :id, :name, :amount, :premium, :protection_length, :paid_period_length, :consider_year, :consider_gender, :company, :reference_id, :book_id json.url book_insurance_url(insurance.book, insurance, format: :json) end
class CreateUserSessions < ActiveRecord::Migration def change create_table :sessions, id: false do |t| t.string :token t.belongs_to :user t.belongs_to :site t.belongs_to :customer t.timestamps end execute %Q{ ALTER TABLE "sessions" ADD PRIMARY KEY ("token"); } end end
class PostsController < ApplicationController before_action :check_password, only: [:destroy] before_action :setup_negative_captcha, only: [:create, :edit, :update] def index @board = Board.find(params[:board_id]) end def new @board = Board.find(params[:id]) @post_form = PostForm.new @board @b...
class ApplicationController < ActionController::Base protect_from_forgery with: :exception before_action :authenticate_user! add_breadcrumb "home", :root_path # load_and_authorize_resource # check_authorization rescue_from CanCan::AccessDenied do |exception| redirect_to main_app.root_path, :alert => ex...
class Pantry attr_reader :stock, :cookbook def initialize @stock = {} @cookbook = [] end def stock_check(item) if @stock[item] == nil return 0 else @stock[item] end end def restock(item, quantity) if @stock[item] == nil @stock[item] = 0 end @stock[item] ...
class IndexUpdaterJob < ApplicationJob queue_as :index_updater def perform(klass_record) klass_record.__elasticsearch__.update_document end end
require 'rails_helper' RSpec.describe UsersController, type: :controller do before do allow_any_instance_of(ApplicationController).to receive(:set_order).and_return double('order') allow_any_instance_of(ApplicationController).to receive(:authenticate_user!).and_return true @ability = Object.new @abil...
feature 'hit points' do # As Player 1, # So I can see how close I am to winning # I want to see Player 2's Hit Points scenario 'see Player 2s HP' do visit('/') fill_in :player_1_name, with: 'Skeletor' fill_in :player_2_name, with: 'Mr Cuddles' click_button 'Submit' expect(page).to have_cont...
require './csvwriter.rb' describe "The CSVWriter class" do it "should be able to write a header row" do writer = CSVWriter.new() data = [{:hash => "ahash", :date => "2012-08-15", "command1" => 1, "command2" => 2}] writer.head(data).should eq('"hash","date","command1","command2"') end it "should be able to ge...
require File.dirname(__FILE__) + '/../test_helper' require 'account_controller' # Re-raise errors caught by the controller. class AccountController; def rescue_action(e) raise e end; end class AccountControllerTest < Test::Unit::TestCase # Be sure to include AuthenticatedTestHelper in test/test_helper.rb instead ...
class ResumesController < ApplicationController def index @students = Student.all render :json => @students, :include => [ :capstones, :educations, :experiences, :skills ] end def new end def create @student = Student.new(student_params) @student.save end de...
[Time, Date, DateTime].map do |klass| klass::DATE_FORMATS[:default] = ->(t) { t.strftime('%Y-%m-%d %H:%M') } klass::DATE_FORMATS[:common] = ->(t) { t.strftime('%Y-%m-%d %H:%M:%S') } klass::DATE_FORMATS[:only_date] = ->(t) { t.strftime('%Y年%m月%d日') } klass::DATE_FORMATS[:flat] = ->(t) { t.strftime('%Y%...
class OutputInput def initialize(input) @input = input end def call input end private attr_reader :input end
class ConsolesController < ApplicationController def index if params[:user_id] @user = User.find(params[:user_id]) @consoles = @user.consoles else @consoles = Console.all end end def new @console = Console.new end def create ...
# == Schema Information # # Table name: cities # # id :integer not null, primary key # name :string # nickname :string # created_at :datetime not null # updated_at :datetime not null # slug :string # class City < ActiveRecord::Base has_many :events has_many :ven...
json.array!(@kato_rooms) do |kato_room| json.extract! kato_room, :id, :Get json.url kato_room_url(kato_room, format: :json) end
class Dashboard::CollaborationStudiosController < DashboardController def index @collaboration_studios = CollaborationStudio.paginate(:page => params[:page]) end def new @collaboration_studio = CollaborationStudio.new end def create @collaboration_studio = current_user.created_collaboration_stu...
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Ch...
require "rails_helper" RSpec.feature "visitor can view current application status" do scenario "sees open when applications are open, otherwise closed" do create(:application, name: "Apprentice.io Developer") create(:application, name: "Full-Time Developer") visit root_path expect(apprentice_io_deve...
# frozen_string_literal: true require 'spec_helper' describe "GraphQL::Cop::DefaultRequiredTrue" do include RubocopTestHelpers it "finds and autocorrects `required: true` argument configurations" do result = run_rubocop_on("spec/fixtures/cop/required_true.rb") assert_equal 4, rubocop_errors(result) a...
# frozen_string_literal: true require 'jiji/test/test_configuration' describe Jiji::Utils::Pagenation::Query do include_context 'use data_builder' let(:time_source) { Jiji::Utils::TimeSource.new } before(:example) do factory = Jiji::Model::Graphing::GraphFactory.new @graph1 = factory.create('test1', :c...
desc "Setup your fort board." task :setup => :environment do if Admin.count >= 1 puts "You have already created an admin." abort else puts "Enter admin password for your board:" pw = STDIN.gets Admin.create(:password => pw) puts "Admin created." end end
class MailLog < ActiveRecord::Base has_many :mail_log_recipient_lists belongs_to :sender, :class_name => "User" serialize :recipients named_scope :logs_between, lambda { |start_date, end_date| {:conditions => ['created_at between ? and ?', start_date.to_date.beginning_of_day, end_date.to_date.end_of_day]} ...
require 'fog/core/collection' require 'fog/aliyun/models/storage/directory' module Fog module Storage class Aliyun class Directories < Fog::Collection model Fog::Storage::Aliyun::Directory def all containers = service.get_containers() if nil == containers re...
require 'integration_spec_helper' describe 'Folder upload' do if account? before(:all) do @storage = login end context "when a folder is uploaded" do let(:folder) { SecureRandom.hex(6) } let(:subfolder_empty) { SecureRandom.hex(6) } let(:subfolder_with_content) { SecureRandom....
# frozen_string_literal: true require 'yaml' require 'set' module CICI class Config def initialize(ui) @ui = ui end def load config_file_name = '.cici.yml' @ui.fail("Cannot find config file, #{config_file_name} in current directory.") unless File.file?(config_file_name) config...
# frozen_string_literal: true require 'test_helper' module XML class EventTest < Minitest::Test def setup @builder = Event.new(event_params) end def test_create_xml xml = @builder.create assert xml.include?('<id source="T2modus.com" sequence="1">1494077439</id>') assert xml.incl...
class Exchange < ActiveRecord::Base attr_accessor :money belongs_to :bought, :class_name => "Currency" belongs_to :sold, :class_name => "Currency" validates :bought_id, :presence => true validates :sold_id, :presence => true validates :money, :numericality => {:greater_than => 0}, ...
#!/usr/bin/env ruby # rubocop: disable Lint/UselessAssignment require_relative '../lib/player1.rb' require_relative '../lib/board.rb' puts ' _______ _ _______ _______ |__ __(_) |__ __| |__ __| | | _ ___ ______| | __ _ ___ ______| | ___ ___ | | | |/ __|______| |/...
module Palindrome def lychrel? !self.palindrome end def palindrome max_tries = 50 result = self tries = 0 until result.palindromic? return nil if tries >= max_tries result += result.reverse tries += 1 end result end def palindromic? self == self.rever...
# frozen_string_literal: true Rails.application.routes.draw do devise_for :admins, path: 'admin', path_names: { sign_in: 'login', sign_out: 'logout', sign_up: 'register' } devise_for :users, path: '', path_names: { sign_in: 'login', sign_out: 'logout', sign_up: 'register' } root 'entries#index' resources :fe...
Gradebook::Reports::Template.config do name 'template_p' display_name 'CBSE template' description 'This template is ideal for a planner having 2 terms.' target_type :school is_default false setting do name 'logo' kind :select options ({'CBSE' => 'cbselogo.png', 'ICSE' => 'icselogo.png', 'Stude...
class StemmerApi def initialize @dictionary = Hash.new("") lines_cs = File.readlines("#{File.dirname(__FILE__)}/../../data/word_list_translated.txt") lines_cs_stemmed = File.readlines("#{File.dirname(__FILE__)}/../../data/word_list_translated_stemmed.txt") 0.upto(lines_cs.size - 1) do |i| wor...
ActiveAdmin.register Post do config.sort_order = 'position_asc' # assumes you are using 'position' for your acts_as_list column sortable # creates the controller action which handles the sorting index do sortable_handle_column # inserts a drag handle # column :position column :identifier column...
#!/usr/bin/ruby # # Read an APNG file, create a sprite sheet # from the frames, and generate example CSS. # Both constant and variable frame delays # are supported. # # Uses both apngdis and optipng, which # you will need in your path. # # never use global variables $vendpfs = ["-webkit-", "-moz-", "-o-", ""] # remov...
require 'rails_helper' RSpec.describe Product, type: :model do describe 'title' do it 'must be present' do p = Product.new(description: "Has absolutely no purpose or use", price: 900) count_before = Product.count p.save count_after = Product.count expect(count_after).to eq(count_be...
class DmChannel < ApplicationRecord has_many :messages, as: :channel has_and_belongs_to_many :users validates :users, length: { is: 2 } end
require 'test_helper' class ActiveFlags::Handler::FlagMapperTest < ActiveSupport::TestCase test 'should authorize and remap flags' do authorized_flags = [:hidden, :visible] hash_of_flags_to_check = {hidden: true, visible: false, dragonball: '4 on 7'} flags = ::ActiveFlags::Handler::FlagMapper.remap(autho...
class CreateFingers < ActiveRecord::Migration def change create_table :fingers do |t| t.integer :user_id, :null => false t.integer :digit, :null => false t.integer :side, :null => false t.decimal :size, :scale => 2, :default => -1, :null => false t.text :comment, :default => "", :nul...
class AddUserTypeToMenus < ActiveRecord::Migration def self.up add_column :menus, :user_type, :integer, :limit => 1, :null => false, :default => 3 end def self.down remove_column :menus, :user_type end end
require 'bson' class BSONInput include Enumerable def initialize(stream=nil) @stream = stream || $stdin end def read begin BSON.read_bson_document(@stream) rescue NoMethodError nil end end def each while(doc = read) yield doc end end end class BSONKeyValu...
require 'test_helper' class WireStoriesControllerTest < ActionDispatch::IntegrationTest setup do @wire_story = wire_stories(:one) end test "should get index" do get wire_stories_url assert_response :success end test "should get new" do get new_wire_story_url assert_response :success e...
class Cask::CLI::List def self.run(*arguments) if arguments.any? list_files(*arguments) else list_installed end end def self.list_files(*cask_names) cask_names.each do |cask_name| cask = Cask.load(cask_name) if cask.installed? Cask::PrettyListing.new(cask).print ...
require 'formula' class ArpackJulia < Formula homepage 'https://github.com/opencollab/arpack-ng' url 'https://github.com/opencollab/arpack-ng/archive/3.3.0.tar.gz' sha256 'ad59811e7d79d50b8ba19fd908f92a3683d883597b2c7759fdcc38f6311fe5b3' revision 4 bottle do root_url 'https://juliabottles.s3.amazonaws.c...
json.array!(@billing_addresses) do |billing_address| json.extract! billing_address, :donator_id, :main_contact, :address1, :address2, :city, :state, :zip, :country json.url billing_address_url(billing_address, format: :json) end
module TryUntil # This PORO holds information about a target object against which # to call a specified method with specified arguments class Probe # Example: Probe.new(SomeClass.new, :some_method, [arg1, arg2, ...]) def initialize(target, method, args = []) @target = target @method = method ...
# Manage systemd services using /bin/systemctl Puppet::Type.type(:service).provide :sabayon, :parent => :systemd do desc "Manages `systemd` services using `systemctl`." defaultfor :operatingsystem => :sabayon end
When(/^node "(.*?)" distributes "(.*?)" Peercoins$/) do |arg1, arg2| #distribute <cutoff timestamp> <amount> [<proceed>] node = @nodes[arg1] time = Time.parse(node.top_block["time"]) @distribution = @nodes[arg1].rpc("distribute", time.to_i, parse_number(arg2)) @supply = node.info["moneysupply"] end Then(/^th...
namespace :db do desc "Fill database with sample data" task populate: :environment do User.create!(name: "Example User", email: "example@eventdb.org", username: "exampleuser", password: "foobar", password_confirmation: "foobar") admin = Use...
class SignLanguage < ActiveRecord::Base validates :acronym, :presence => true, :uniqueness => true validates :name, :presence => true has_many :signs has_many :meanings, :through => :signs default_scope order('sign_language.acronym') end
module TournamentsHelper def tournament_date(date) date.strftime('%m/%d/%Y %I:%M %p') end def single_elim_winner(tournament) last = tournament.winners_bracket.last last.winner if last.winner end def single_elim_runner_up(tournament) last = tournament.winners_bracket.last last.loser if la...
class Meal < ApplicationRecord belongs_to :restaurant validates :name, :description, :price, :restaurant, :hide, :presence => true end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Ch...
class ApplicationController < ActionController::Base protect_from_forgery with: :exception def current_user User.find_by(id: session[:user_id]) end def user_logged_in? current_user.present? end def authenticate_user! unless user_logged_in? flash[:alert] = "You must be signed in to do tha...
class ContestantsController < ApplicationController before_filter :authenticate_contestant! def index @contestant = current_contestant if @contestant.admin? redirect_to admin_root_path and return end @favourites = Photo.find(@contestant.voted_photo_ids || []) @votes_left_today = V...
class CreateTableOrders < ActiveRecord::Migration[5.0] def change create_table :orders do |t| t.string :code t.integer :customer_id t.float :total t.integer :item_total t.string :email t.string :phone t.string :address t.string :name t.string :last_name end end e...
# frozen_string_literal: true module Helpers module Json def parsed_body if respond_to?(:response_body) JSON.parse(response_body, symbolize_names: true) else JSON.parse(response.body, symbolize_names: true) end end def jsonapi_params(type: nil, attributes: {}, relations...
class ApplicationController < ActionController::Base protect_from_forgery helper_method :current_user before_filter :set_locale def set_locale # 可以將 ["en", "zh-TW"] 設定為 VALID_LANG 放到 config/environment.rb 中 if params[:locale] && I18n.available_locales.include?( params[:locale].to_sym ) sessi...
# -*- coding: utf-8 -*- class TimelineEventObserver < ActiveRecord::Observer def after_create(timeline_event) # User Followers user = timeline_event.actor followers = user.followers.map_user create_timelines(followers, timeline_event, :ownerable_type => timeline_event.actor_type,...
# -*- encoding : utf-8 -*- # The model of the artist resource. # # This code is part of the Stoffi Music Player Project. # Visit our website at: stoffiplayer.com # # Author:: Christoffer Brodd-Reijer (christoffer@stoffiplayer.com) # Copyright:: Copyright (c) 2013 Simplare # License:: GNU General Public License (stoff...
When /^I pick my seat "([^"]*)"$/ do |seat_id| save_and_open_page fill_in 'seat', :with => seat_id click_button('submit') end
class PipelineAggregator::JenkinsCache < PipelineAggregator::Base def initialize(config_data) @config_data = config_data # TODO Validate config file is correct # Create data dirs if it doesn't exist Dir.mkdir(jobs_directory) unless File.directory?(jobs_directory) Dir.mkdir(builds_directory) unl...
# Write a method that takes a single String argument and returns a new string that contains the original value of the argument with the first character of every word capitalized and all other letters lowercase. # You may assume that words are any sequence of non-blank characters. =begin approach: - split the senten...
require 'nokogiri' module Vault::Test::HTMLHelpers # Save and open an HTML document in your browser. # # @param html [String] The page to open or nil to fetch it from # `last_response.body` if testing a Sinatra app. def save_and_open_page(html = nil, name = 'page.html', i = 1) html ||= last_response.bo...
class Bartender < ApplicationRecord belongs_to :bar has_many :orders has_many :users, through: :orders has_secure_password end
require File.join(File.dirname(__FILE__), '..', '..', 'spec_helper') include Zheng describe Zheng::Actions::Player do describe "add" do before do @p1 = mock("player1", :name => "Peter", :rating => 2400) @p2 = mock("player2", :name => "John", :rating => 2400) @g = mock("game") @g.stub!(:a...
class Parser DEBUG = false SHOWNAMES = ["Fake News The Musical"] SHOWREGEXES = [/Storytelling Night/i, /666 Project/i, /IMPROVAGEDDON/i, /Improvised Fairy Tale/i, /Date Night/i, /Monocle/i, /Tales from the Campfire/i, /SKETCHMAGEDDON/i, /The Unusual Suspects/i, /Improv Riot/i, /Class Dismissed/i, /Girl-Prov/i, /S...
class CreateClients < ActiveRecord::Migration def self.up create_table "clients", :force => true do |t| t.string "email", :default => "", :null => false t.string "name" t.string "phone" t.text "mailingaddress" t.timestamps end add_index "clients", ["email...
class CreateUnder < ActiveRecord::Migration def self.up create_table :unders do |t| t.string :studentid t.string :sid t.string :bdate t.timestamps end end def self.down drop_table :unders end end
# == Schema Information # # Table name: steps # # id :integer not null, primary key # description :text # recipe_id :integer # created_at :datetime not null # updated_at :datetime not null # class Step < ActiveRecord::Base attr_accessible :description, :recipe_id, :step_ing...
require('minitest/autorun') require('minitest/rg') require_relative('../hidden_word.rb') require_relative('../game.rb') require_relative('../player.rb') class HiddenWordTest < MiniTest::Test def setup # @hidden_word_1 = HiddenWord.new("Hidden", "e") # # @hidden_word_2 = HiddenWord.new("Hidden", "z") ...
class Artist attr_accessor :name, :song #apparently these things are methods themselves just making them is enough for certain things to work. @@all = [] #this represents all artist. def initialize @name @@all << self end def self.all @@all end def name=(name) @name = name end def song ...
class User < ActiveRecord::Base attr_accessible :email validates_presence_of :email, :on => :create validates_uniqueness_of :email, :message => "must be unique" has_many :todo_lists end
class Description::RDS < Description def initialize(description) description[:service] ||= :rds @description = description end def name aws_id end def region_zone availability_zone end def logical_zone # parse from name if not multi_az, otherwise nil super unless multi_az end ...
class Result attr_reader :home, :guest def initialize(home,guest) @home, @guest = home, guest end def == (other_score) (home == other_score.home && guest == other_score.guest) || (home == other_score.guest && guest == other_score.home) end def toto home <=> guest end end
class User < ActiveRecord::Base before_save {self.email = email.downcase} before_create :create_remember_token def User.new_remember_token SecureRandom.urlsafe_base64 end def User.encrypt(token) Digest::SHA1.hexdigest(token.to_s) end private def create_remember_token self.remember_tok...
class User < ApplicationRecord validates :username, length: { minimum: 5, maximum: 20 } has_many :comments has_many :posts end