text
stringlengths
10
2.61M
module Chronic class Arrow BASE_UNITS = [ :years, :months, :days, :hours, :minutes, :seconds ] UNITS = BASE_UNITS + [ :miliseconds, :mornings, :noons, :afternoons, :evenings, :nights, :midnights, :weeks, :weekdays, ...
class AlterBikeWheelToId < ActiveRecord::Migration def up add_column :bikes, :bike_wheel_size_id, :integer undetermined_id = BikeWheelSize.find_by_rdin("0") Bike.find_each do |bike| wheel_size = BikeWheelSize.find_by_rdin(bike['wheel_size'].to_s) if wheel_size.nil? wheel_size_id = un...
RSpec.shared_examples "failed authentication" do it "redirects to /users/sign_in" do subject expect(response).to redirect_to("/users/sign_in") end end RSpec.shared_examples "failed routing" do it "raises a routing error" do expect { subject }.to raise_error(ActionController::RoutingError) end end
require 'test_helper' class Liquid::Drops::ApplicationPlanDropTest < ActiveSupport::TestCase context 'ApplicationPlanDrop' do setup do @plan = FactoryBot.create(:application_plan) 2.times { |u| FactoryBot.create(:usage_limit, :plan => @plan) } @drop = Liquid::Drops::ApplicationPlan.new(@plan) ...
class State < ActiveRecord::Base has_many :institutions belongs_to :region validates :name, :abbreviation, presence: true end
require "banxico/sie/version" require "banxico/sie/connection" require "banxico/sie/client" require "banxico/sie/endpoints" require "banxico/sie/usd_exchange_rate" require "banxico/sie/errors/base_error" require "banxico/sie/errors/network_error" module Banxico module SIE def self.config yield self end...
class RenameMcoIdOnMcos < ActiveRecord::Migration def change rename_column :mcos, :mco_id, :bwc_mco_id end end
module API module V1 class Properties < Grape::API include API::V1::Defaults helpers PropertyHelpers resource :properties, desc: 'Properties Endpoint' do desc 'Return the most Viewed Properties.' get '/most-viewed' do present Property.most_viewed, with: API::V1::Entiti...
FactoryGirl.define do factory :problem do text { Faker::StarWars.quote } setup { Faker::StarWars.quote } function_name { Faker::Space.agency_abv } association :user, factory: :user association :language, factory: :language end end
class AddProcessedAtToPerson < ActiveRecord::Migration def change add_column :people, :processed_at, :datetime add_index :people, :processed_at end end
class Attachment < ActiveRecord::Base mount_uploader :file, FileUploader before_create do self.original_file = self.file.original_file end end
RSpec.describe Hcheck::Checks::Postgresql do include Hcheck::Checks::Postgresql describe '#status' do let(:test_config) do { host: 'PG_DB_HOST', dbname: 'PG_DBNAME', user: 'PG_DB_USER', password: 'PG_DB_PASSWORD' } end let(:pg_connection) { double('PG::Connec...
class ClientsController < ApplicationController def new @client = Client.new end def create @client = Client.new(client_params) if verify_recaptcha(model: @client) && @client.valid? ClientMailer.new_client(@client).deliver unless client_params[:honey].present? redirect_to thank_you_path, ...
###################################################################### # Copyright (c) 2008-2014, Alliance for Sustainable Energy. # All rights reserved. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free...
class Brand < ActiveRecord::Base has_many :models def device_count models.collect{ |m| m.device_count }.sum end end
=begin Write a method that can rotate the last n digits of a number. For example: =end def rotate_array(ary) new_ary = ary.dup first_item = new_ary.shift new_ary.push(first_item) new_ary end # Option A: def rotate_rightmost_digits(num, n_last_digits) return num if n_last_digits <= 1 ary_of_digits = num.d...
class Evil::Client::Middleware class MergeSecurity < Base private def build(env) env.dup.tap do |hash| security = hash.delete(:security).to_h %i(headers body query).each do |key| next unless security[key] hash[key] ||= {} hash[key].update security[key] ...
module DateOutput module ViewHelpers def full_date_with_time(date,options={}) DateOutput.full_date_with_time(date,options) end def short_date_with_time(date,options={}) DateOutput.short_date_with_time(date,options) end def numbered_date_with_time(date,options={}) DateOutpu...
require 'nokogiri' require 'open-uri' class GetSnapcodeImageFromExternalApi FetchingFailed = Class.new(StandardError) def call(snapchat_username) image = Nokogiri::XML(open(api_url_for_image(snapchat_username))) image.to_html rescue OpenURI::HTTPError raise FetchingFailed end private def api...
#encoding: utf-8 module UsersHelper def change_account_display_or_not code = <<-ACCOUNTFIELD $(function(){ $('#isappuser').click(function() { if($('#isappuser').is(":checked")) { $('#account_field').attr("class", "control-group"); } else { $('#account_fie...
class RecreateInventories < ActiveRecord::Migration def change create_table :inventories do |t| t.integer :order_line_id t.timestamps end end end
class ProductsController < ApplicationController def who_bought @product = Product.find(params[:id]) respond_to do |format| format.atom end end def index @products = Product.all end def new @product = Product.new end def create @product = Product.new(product_params) if @product.sav...
class CreateOrganizationProfileViews < ActiveRecord::Migration def self.up create_table :organization_profile_views, :id => false do |t| t.integer :viewer_id t.integer :organization_id t.datetime :created_at end end def self.down drop_table :organization_profile_views end end
require 'rails_helper' RSpec.describe Path do subject { described_class.new } it { is_expected.to have_many(:users) } it { is_expected.to have_many(:path_courses).order(:position) } it { is_expected.to have_many(:courses).through(:path_courses) } it { is_expected.to validate_presence_of(:title) } it { is...
class ArtistTagsController < ApplicationController before_action :set_artist def new @artist_tag = ArtistTag.new end def create names = params[:artist_tag][:tag].reject(&:empty?).map(&:downcase) names.each do |name| tag = Tag.find_or_create_by(name: name) ArtistTag.create(artist: @arti...
class NotAffectingInvestment NOT_AFFECTING_INVESTMENT = { 'f[]' => 'issue.cf_20', 'op[issue.cf_20]' => '!', 'v[issue.cf_20][]' => 0 }.freeze def array_queries NOT_AFFECTING_INVESTMENT.map { |key, value| [key, value] } end def hash_queries NOT_AFFECTING_INVESTMENT end end
#!/usr/bin/env ruby require "rubygems" require 'sdl' require_relative 'board.rb' class Principal def initialize SDL.init SDL::INIT_VIDEO @screen = SDL.set_video_mode 806, 604, 0, 0 @tabuleiro = SDL::Surface.load "Tabuleiro.png" @peca = SDL::Surface.load "Bloco.png" @peca2 = SDL::Surface.load "Bl...
class Recipe < ActiveRecord::Base has_many :recipe_ingredients has_many :ingredients, through: :recipe_ingredients validates_presence_of :name accepts_nested_attributes_for :ingredients, reject_if: lambda {|attributes| attributes['name'].blank?} def ingredients_attributes=(ingredients_attributes) ingred...
def T_WHITESPACES(value) { type: 'T_WHITESPACES', value: value } end T_COMMA = { type: 'T_COMMA', value: ',' } T_COLON = { type: 'T_COLON', value: ':' } T_SEMICOLON = { type: 'T_SEMICOLON', value: ';' } T_OPEN_ROUND_BRACKET = { type: 'T_OPEN_ROUND_BRACKET', value: '(' } T_CLOSE_ROUND_BR...
# # Copyright 2009 Huygens Instituut for the History of the Netherlands, Den Haag, The Netherlands. # # This file is part of New Women Writers. # # New Women Writers is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundat...
# frozen_string_literal: true # rubocop:todo all require 'spec_helper' describe Mongo::Operation::Indexes do require_no_required_api_version let(:context) { Mongo::Operation::Context.new } describe '#execute' do let(:index_spec) do { name: 1 } end before do authorized_collection.drop...
class CreateDiscipleEquipments < ActiveRecord::Migration def change create_table :disciple_equipments, options: 'ENGINE=INNODB, CHARSET=UTF8' do |t| t.integer :disciple_id, default: -1 t.integer :equipment_id, default: -1 t.timestamps end end end
class User < ActiveRecord::Base validates :name, presence: true, length: { in: 1..10 }, uniqueness: true validates :password, presence: true, length: {minimum: 1, maximum: 6 } def self.login(name, password) find_by(name: name, password: password) end def try_login find_user = User.login(self.name, ...
require 'aws/templates/utils' module Aws module Templates module Help module Rdoc module Parametrized module Constraints ## # Case-like constraint documentation provider # # Prints all handled value and respective constraints. cl...
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :token_authenticatable, :confirmable, # :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, ...
# https://github.com/stormasm/sds-warden/blob/rediswarden/doc/redisapi.md # Tokens map to account and project # Accounts map to Dbs # You can have multiple projects in a DB, but not multiple accounts require 'json' require 'redis' require_relative './redisoptions' class RedisData def initialize @redisc ||= Red...
class Client < ApplicationRecord validates :name, :num_dogs, :dogs, presence: true has_many :bookings end
module CoinsExtensions refine Array do def can_return_coin?(change) raise 'change < 0' if change < 0 tmp = self.dup return {change_coins:[], rest_coins:tmp} if 0 == change if tmp.include? change tmp.delete_at(tmp.index(change)) return {change_coins:[chan...
class UsersController < ApplicationController before_action :redirect_if_logged_out skip_before_action :redirect_if_logged_out, only: [:new, :create, :index] before_action :disable_forum_style, except: [:index] def new redirect_if_logged_in @user = User.new end def create ...
class CreateEvaluations < ActiveRecord::Migration[5.2] def change create_table :evaluations do |t| t.string :evaluation_name t.integer :evaluation_numeric_number t.datetime :deleted_at t.timestamps end end end
class LogEntry < ActiveRecord::Base belongs_to :loggable, :polymorphic => true belongs_to :company belongs_to :user belongs_to :customer, :class_name => 'User' # LogEntries must be associated with a company. We usually capture the user who created the eve...
class BidIsHighEnoughValidator < ActiveModel::Validator def validate(bid) unless bid.round.has_no_bids_yet? || higher_than_current_highest_bid?( bid.suit, bid.number_of_tricks, bid.round.highest_bid ) bid.errors.add(:base, "your bid isn't high eno...
require 'rspec' describe 'No Subscription' do it 'price should be zero' do subscription = NoSubscription expect(subscription.price).to eq 0 end it 'does not have mentoring' do subscription = NoSubscription.new expect(subscription.has_mentoring?).to be_false end it 'does not charge the cr...
class GraphqlCrudOperations def self.type_mapping proc do |_classname| { 'str' => types.String, '!str' => !types.String, 'int' => types.Int, '!int' => !types.Int, 'id' => types.ID, '!id' => !types.ID, 'bool' => types.Boolean, 'json' => JsonStri...
class Need < ApplicationRecord attribute :is_taken, :boolean, default: false attribute :datetime_range_start, :datetime, default: DateTime.now attribute :datetime_range_end, :datetime, default: DateTime.now.end_of_day end
class Material::File < ActiveRecord::Base attr_accessible :file, :material, :material_id belongs_to :material mount_uploader :file, MaterialFileUploader def name @name ||= File.basename file.url end end
require 'rails_helper' RSpec.describe 'Services', type: :request do before(:all) do Jurisdiction.all.map(&:destroy) Service.all.map(&:destroy) @good_service = Fabricate(:service) end describe 'GET /services' do it 'returns a collection' do get services_path expect(response).to have_...
require_relative '../lib/parser_log.rb' describe ParserLog do let(:expected_output) { File.open(File.dirname(__FILE__) + '/support/results.txt').read } let(:parser_log) { ParserLog.new(File.dirname(__FILE__) + '/support/webserver.log') } it "initialize parser with file" do expect(parser_log).to_not be nil ...
FactoryGirl.define do factory :asset_type do |at| at.name 'Laptop' end factory :asset do |a| a.asset_id 'asset id' a.purchase_date Time.now a.serial_number '1234' a.make_year Time.now a.description 'This is description' a.display_size 15 a.manufacturer 'HP' a.model 'TEST-123' ...
class Authentication::LocalsController < ApplicationController before_action :set_authentication_local, only: [:show, :edit, :update, :destroy] before_action :logged_in_user, only: [:index, :show, :edit, :update, :destroy] def index @authentication_locals = Authentication::Local.all end def show end...
class Expense < ActiveRecord::Base belongs_to :category has_and_belongs_to_many :tags validates :price, numericality: true, presence: true validates :name, presence: true end
require "formula" class Ruby19Dependency < Requirement fatal true default_formula "ruby" satisfy do `ruby --version` =~ /ruby (\d\.\d).\d/ $1.to_f >= 1.9 end def message "Betty requires Ruby 1.9 or better." end end class Betty < Formula homepage "https://github.com/pickhardt/betty" url "...
FactoryGirl.define do sequence :metasploit_model_architecture_abbreviation, Metasploit::Model::Architecture::ABBREVIATIONS.cycle sequence :metasploit_model_architecture_bits, Metasploit::Model::Architecture::BITS.cycle sequence :metasploit_model_architecture_endianness, Metasploit::Model::Architecture::ENDIANNESS...
class CreateEditionsWorks < ActiveRecord::Migration def change create_table :editions_works, :id => false do |t| t.integer :edition_id t.integer :work_id end end end
Pod::Spec.new do |s| s.name = "ObjectiveCOAuth1Consumer" s.version = "0.0.1" s.summary = "OAuth1.0a Framework for Dealing with the Yelp API's Quirky '2-Legged' OAuth Variant" s.description = "Yelp requires a weird variant of 2-legged OAuth from a client trying to access it's API. The API h...
module RbacCore::Concerns module OptionsModel module Serialization extend ActiveSupport::Concern def to_h hash = {} self.class.attribute_names.each do |attribute_name| attribute = public_send(attribute_name) if attribute.is_a?(self.class) hash[attribut...
class AddColumnsToBanks < ActiveRecord::Migration def change add_column :banks, :money_id, :integer add_column :banks, :account_type, :string add_column :banks, :account_number, :string add_column :banks, :account_detraction, :string add_column :banks, :cci, :string end end
class DogsController < ApplicationController before_action :set_dog, only: [:show, :edit, :update, :destroy] # Runs set_dog before only the show, edit, and update methods def index @dogs = Dog.all end def new @dog = Dog.new end def create @dog = Dog.new(dog_params) # if saves, go to index w/ notifi...
require 'linkedlist/version' require 'date' module Ref # Clase Referencia class Referencia include Comparable # Se tiene acceso de lectura y escritura a todos los atributos attr_accessor :titulo, :autores, :fec, :pa, :an, :edit, :edic, :vol def initialize(titulo, &block) # Comprobamos tipo ...
ActiveAdmin.register Category do menu :parent => "Admin resource", label: 'Courses Categories' index do column :id column :name, :sortable => :name do |c| link_to c.name, admin_category_path(c) end column :parent do |c| link_to c.parent.name, admin_category_path(c) if c.parent.present? ...
require 'spec_helper' describe SubscriptionsController do describe "GET 'unsubscribe'" do def do_request(params = {}) get :unsubscribe, params end it "finds subscription with given token" do Subscription.should_receive(:find_by_hash_key).with('foo') do_request :id => 'foo' end ...
class Response < ActiveRecord::Base belongs_to :user belongs_to :respondable, :polymorphic=>true has_many :votes, :as => :votable validates :body, :respondable_id, :respondable_type, :presence=>true validates :respondable_type, :inclusion => { :in => %w(Question Answer), :message => "%{value} is not a ...
require './contact_menu' require './modify_menu' require './contact.rb' class MainMenu #attr_accessor :contact def initialize @done = false @menu = [ "\e[H\e[2J", "---- Main Menu ----".center(25), "1. Add New Contact", "2. Display Contacts", "3. Modify A Contact", "0. QUIT", ] end ...
module CarrierWave class SanitizedFile # FIXME (Did) CarrierWave speaks mime type now def content_type_with_file_mime_type mt = content_type_without_file_mime_type mt.blank? || mt == 'text/plain' ? File.mime_type?(original_filename) : mt end alias_method_chain :content_type, :file_mime_...
require 'mysql2' class Server def initialize(mysql_config) @mysql_config = mysql_config end def with_connection yield(mysql_client) mysql_client.close end private def mysql_client @mysql_client ||= Mysql2::Client.new(@mysql_config) end end config = { username: "root", password: ""...
# frozen_string_literal: true require_relative 'lib/riteway/version' Gem::Specification.new do |spec| spec.name = 'riteway' spec.version = Riteway::VERSION spec.authors = ['Mikey Hargiss'] spec.summary = 'Simple, readable, helpful unit tests in Ruby' spec.license = 'MIT' ...
module Assistant class SharesController < InheritedResources::Base InheritedResources.flash_keys = [ :success, :failure ] before_filter :authenticate_user! actions :all, :only => [:new, :create] respond_to :html defaults :route_prefix => 'assistant' def new @share = current_user.shares....
share_examples_for 'It can transfer a Resource from another association' do before :all do @no_join = defined?(DataMapper::Adapters::InMemoryAdapter) && @adapter.kind_of?(DataMapper::Adapters::InMemoryAdapter) || defined?(DataMapper::Adapters::YamlAdapter) && @adapter.kind_of?(DataMapper::Adapt...
FactoryBot.define do factory :notification_preference do notification_type { NotificationPreference::SIGNUP } notification_frequency { NotificationPreference::IMMEDIATELY } association :user, factory: :user factory :organization_notification_preference do association :settable, factory: :organi...
# == Schema Information # # Table name: questions # # id :integer not null, primary key # survey_id :integer # label :string(255) # position :integer # created_at :datetime not null # updated_at :datetime not null # class Question < ActiveRecord::Base attr_accessible :l...
##### # @author Mars ##### require 'test_helper' class ImageTest < ActiveSupport::TestCase test "should not save image without an image url" do image = Image.new assert_not image.save, "Saved image without url" end end
module LoggingExtensions # Create our default log formatter so that we can use it everywhere, and keep formats consistent. def self.default_log_formatter @default_log_formatter = if Rails.env.development? || Rails.env.profiling? || Rails.env.test? Ougai::Formatters::Readable.new else Ougai::Form...
module Entities class New < Grape::Entity expose :title expose :details expose :img_dir expose :img_num expose :date expose :important end end
FactoryGirl.define do factory :user do first_name "John" last_name "Smith" sequence(:email) { |n| "#{first_name}.#{last_name}.#{n}@example.com".downcase } password "secret" password_confirmation { password } password_recovery_token "secret_token" password_recovery_sent_at Time.zone.now e...
class AddForfeitAllMatchesWhenRosterDisbandsOptionToLeagues < ActiveRecord::Migration[5.0] def change add_column :leagues, :forfeit_all_matches_when_roster_disbands, :boolean, null: false, default: true end end
#!/usr/bin/env ruby # # Node visualiser for IF engine. # # Grapher requires svg2png installed on OSX # brew install svg2png if you have homebrew installed require 'graph' class Node < OpenStruct def graph(gr=Graph.new) gr.edge tag.to_s, parent.tag.to_s unless parent.nil? gr.node_attribs << gr.filled ...
require 'rails_helper' RSpec.describe ReferralCode, type: :model do context 'when being created' do it 'generates three profiles' do ref_code = FactoryBot.create(:referral_code) expect(ref_code.code).to match(/^[a-z]{8}$/) end end end
# Things to Test ----- # Ensure that create_map returns a generated map with all the expected attributes. # Ensure that create_map returns a map with a level that it's given. # Ensure create_map returns a map at level 1 without a level given. # Ensure that create_map returns a map with the number of rooms sent in. req...
module WSDL module Reader class PortTypes < Hash def lookup_operation_message(type, operation, messages) # TODO: lookup_message_by_operation each do |_, port_type| message = port_type.lookup_operation_message type, operation, messages return message if message end e...
require 'test_helper' class PetsControllerTest < ActionDispatch::IntegrationTest setup do @pet = pets(:one) end test "should get index" do get pets_url, as: :json assert_response :success end test "should create pet" do assert_difference('Pet.count') do post pets_url, params: { pet: {...
class BatchDefinitions::LaunchEmrCluster < BatchDefinition def initialize() super("launchemr", "BatchLaunchEMRCluster", [Properties::Dynamo.new().withCreateBatchManifestTable(), Properties::LaunchEmr], ["lambda-emr-launch"]) end end
class AddFlagFct280ToMpoints < ActiveRecord::Migration[5.0] def change add_column :mvalues, :fct280, :boolean end end
# frozen_string_literal: true require 'rails_helper' RSpec.describe SentenceHelper, type: :helper do context ".smart_sentence" do let(:wrapper) { ->(k) { k } } let(:options) { {} } let(:sentence) { [] } subject { helper.smart_sentence(sentence, options, wrapper) } it { is_expected.to eq "" } ...
#This file provides the basic environment for cucumber steps to work with. #Permits use of the project's libraries in step definitions. $LOAD_PATH << File.expand_path('../../lib', __FILE__)
class CloudspaceChat::HandleMessages < ApplicationController # connect a user and give them permission to post def connect @current_room_user = CloudspaceChat::CurrentRoomUser.find_by_user_id_and_room_id(current_user.id, params[:room_id]) if @current_room_user.nil? @current_room_user = CloudspaceChat...
require("minitest/autorun") require("minitest/rg") require_relative("../bank_account.rb") class TestBankAccount < MiniTest::Test def setup() @account = BankAccount.new("Ally", 500, "Business") end def test_account_name() assert_equal("Ally", @account.holder_name()) end def test_account_balance()...
class LatestBloodPressuresPerPatientPerQuarter < ApplicationRecord include BloodPressureable scope :with_hypertension, -> { where("medical_history_hypertension = ?", "yes") } def self.refresh Scenic.database.refresh_materialized_view(table_name, concurrently: true, cascade: false) end belongs_to :patien...
class AppointmentsController < ApplicationController def show @appointment = Appointment.find(params[:id]) end def new @appointment = Appointment.new @appointment.doctor.build @appointment.patient.build end def create appointment = Appointment.create(appointment_params) redirect_to...
class AddBannedToIdentities < ActiveRecord::Migration[6.0] def up add_column :identities, :banned, :boolean, :null => false, :default => :false end def down remove_column :identities, :banned end end
class PostsController < ApplicationController before_action :set_user before_action :set_event def index json_response(Post.all) end def create @event.posts.create!(user_id: @user.id, content: params[:content], image_url: params[:image_url]) json_response(@event, :created) end def destroy post = ...
class GeneralExpenses::LoansController < ApplicationController before_filter :authenticate_user!, :only => [:index, :new, :create, :edit, :update ] protect_from_forgery with: :null_session, :only => [:destroy, :delete] def new @costcenters = CostCenter.where('id not in ('+ params[:cc_id]+')') @cc = CostCe...
# encoding: US-ASCII require 'fs/ext4/group_descriptor_table' require 'fs/ext4/inode' require 'binary_struct' require 'uuidtools' require 'stringio' require 'memory_buffer' require 'rufus/lru' module Ext4 # //////////////////////////////////////////////////////////////////////////// # // Data definitions. Linux...
module SQLHelpers # # This is useful for breaking up the recording time in various time-periods in SQL. # It takes the recorded_at (timestamp without timezone) and truncates it to the beginning of the month. # # Following is the series of transformations it applies to truncate it in right timezone: # # * ...
module Finance module PortfolioStatisticsGenerator extend self def statistics_for_allocation(allocation, return_source=:implied_return) securities_hash = summarize_security_data_for(allocation, return_source) expected_return = calculate_expected_return_for(securities_hash) expected_std...
require "cc/engine/analyzers/command_line_runner" require "timeout" require "json" module CC module Engine module Analyzers module Python class Parser < ParserBase attr_reader :code, :filename, :syntax_tree def initialize(code, filename) @code = code @fi...
class Executive < Employee attr_accessor :percentage DEFAULT_PERCENTAGE = 0.10 def initialize(name, percentage = DEFAULT_PERCENTAGE) @percentage = percentage super name end def pay(profits) total_pay = profits * @percentage end end
require 'spec_helper' require "rails_helper" describe ReviewsController, :type => :controller do context "change_approve_reply" do before do @user1 = create(:user, {email: "dieuit07@gmail.com"}) user2 = create(:user) @admin = create(:user, {admin_role: true}) @restaurant = create...
#Inspired by Kirupa's Flash Snow flakes (still looking for license) include System::Windows::Shapes include System::Windows::Controls include System::Windows::Media class SnowMaker def initialize(container, maker_options={}) @options = {:total_flakes=>40, :width=>800, :height=>600}.merge!(maker_options) ...
class Route < ActiveRecord::Base has_many :participants has_many :users, :through => :participants, :source => :user validates :name, :presence => true, :uniqueness => true,:length => {:minimum => 5, :maximum => 70} validates :description, :presence => true, :length => {:minimum =...
class User < ApplicationRecord before_save {email.downcase!} # 省略してかけるが,まだわかりにくいので()つきで書く # validates :name, presence: true validates(:name, presence: true, length: { maximum: 50 } ) VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i validates(:email, presence: tr...