text
stringlengths
10
2.61M
# frozen_string_literal: true # Phone contains format for phone validation class Phone FORMAT = { numericality: true, length: { minimum: 10, maximum: 15 } }.freeze end
require 'spec_helper' require_relative '../../../lib/paths' using StringExtension module Jabverwock RSpec.describe 'doctype test' do subject(:d){DOCTYPE.new} it "confirm name" do expect(d.name ).to eq "doctype" end it "press" do expect(d.tgStr).to eq "<!DOCTYPE html>" end ...
module WithinHelpers def with_scope(locator) locator ? within(locator) { yield } : yield end end World(WithinHelpers) Given(/^I am at the edit meet page$/) do visit root_path with_scope("table") do click_link('More Info', match: :first) end click_link('Edit Meet', match: :first) end ...
class AddMpoincountToFilial < ActiveRecord::Migration[5.0] def change add_column :filials, :mpoints_count, :integer add_column :furnizors, :mpoints_count, :integer end end
# frozen_string_literal: true require 'test_helper' class PersonNameTest < ActiveSupport::TestCase test 'returns a fullname' do pn = PersonName.new('A', 'B', 'C', 'N', 'S', 'H') assert_equal 'A B C', pn.fullname end test 'returns a sortable_name' do pn = PersonName.new('A', 'B', 'C', 'N', 'S', 'H')...
# frozen_string_literal: true require 'openssl' def print_files_in_patch(patch_file_path) parser = OpenSSL::ASN1.decode(File.read(patch_file_path)) files_node = parser.entries.find { |node| node.tag == 601 } files = files_node&.value&.entries || [] files.each do |node| filename_node = node.value.entries....
class AddIndexToPhoneBookEntry < ActiveRecord::Migration def change add_index :phone_book_entries, :first_name add_index :phone_book_entries, :last_name add_index :phone_book_entries, :organization add_index :phone_book_entries, :first_name_phonetic add_index :phone_book_entries, :last_name_phonet...
require 'rails_helper' RSpec.describe Content, type: :model do let(:test_content) { p FactoryGirl.create(:content)} describe '* Attributes *' do it 'has valid attributes' do expect(test_content).to be_valid end end describe '* Validations *' do it 'should validate presence of attributes' do...
module Api module V1 class PostsController < ApplicationController respond_to :json api :GET, '/users/:user_id/topics/:topic_id/posts', "Show User Posts" api_version "1.0" param :posts, Hash do param :user_id, :number, :required => true param :topic_id, :number, :req...
module CSSPool module CSS class MediaQueryList < CSSPool::Node attr_accessor :media_queries, :parse_location, :rule_sets def initialize(media_queries = [], parse_location = {}) @media_queries = media_queries @parse_location = parse_location @rule_sets = [] end def...
class GuestsController < ApplicationController def create @event = Event.find(params[:event_id]) @token = SecureRandom.urlsafe_base64 @guest = Guest.new(name: params[:guest][:name], email: params[:guest][:email], event_id: @event.id, token: @token) @guest.save GuestMailer.guest_invitation(@event,...
require 'pry' # require 'node' NODES = [] def setup size(640, 480) fill(0, 0, 0, 0) range = 50 (0..range).each do |i| NODES.push(Node.new(i, random(width), random(height), (0..range).to_a.sample(random(range)))) end end def draw background(255) NODES.each do |n| n.draw_node n.draw_connect...
class DummyMedicamentsController < ApplicationController before_action :authenticate_user! before_action :set_dummy_medicament, only: [:show, :edit, :update, :destroy] # GET /medicaments # GET /medicaments.json def index @dummy_medicaments = DummyMedicament.all render layout: "dashboard" end d...
class Tweet < ActiveRecord::Base belongs_to :user validates_presence_of :user validates_presence_of :message validates_length_of :message, minimum: 2, maximum: 140 def self.time_line user sql = "select t.* from tweets as t inner join users as u on t.user_id = u.id where u.id =...
# Taken from "Cloning Internet Applications with Ruby" require 'data_mapper' class User include DataMapper::Resource property :id, Serial property :email, String, :length => 255 property :nickname, String, :length => 255 property :formatted_name, String, :length => 255 property...
class User < ApplicationRecord has_and_belongs_to_many :events devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable, :confirmable, :lockable validates :name, presence: true end
class StudentsController < ApplicationController # before_action :set_student, only: [:show, :activate, :update, :destroy] def index @students = Student.all end def show @student = Student.find(params[:id]) end def activate @student = Student.find(params[:id]) @student.active = !@student....
class AddFlagToKnotebooks < ActiveRecord::Migration def self.up add_column :knotebooks, :ignore, :boolean, :default => false Knotebook.with_exclusive_scope do Knotebook.update_all("ignore = false") end end def self.down remove_column :knotebooks, :ignore end end
Rails.application.routes.draw do root 'static_pages#home' get '/about', to: 'static_pages#about' get '/help', to: 'static_pages#help' get '/contacts', to: 'static_pages#contacts' resources :sites do resources :forms end resources :forms end
class Referral < ActiveRecord::Base attr_accessible :referred_id, :referrer_id, :contest_id belongs_to :referrer, class_name: "User", foreign_key: "referrer_id" belongs_to :referred, class_name: "User", foreign_key: "referred_id" belongs_to :contest end # == Schema Information # # Table name: referrals # # ...
json.array!(@weight_units) do |weight_unit| json.extract! weight_unit, :id, :name json.url weight_unit_url(weight_unit, format: :json) end
require 'movie_fetcher' class Movie < ActiveRecord::Base has_many :movie_entries validates :title, presence: true default_scope { order("title ASC") } def self.find_or_create_by_title(title) title = title.downcase.titleize movie = Movie.find_by_title(title) if movie movie else # mak...
module MCollective module Agent class Agentinfo<RPC::Agent # Get actions, inputs, outputs of agents action "desc" do validate :agentname, String ddl = MCollective::RPC::DDL.new(request[:agentname]) actionhash = Hash.new ...
require "upload_image_retain_low_quality/version" require 'upload_image_retain_low_quality' require 'upload_image_retain_low_quality/console' require 'upload_image_retain_low_quality/image' require 'upload_image_retain_low_quality/s3' require "aws-sdk" require "mini_magick" require 'optparse' require "yaml" require 'p...
context = KnifeContainer::Generator.context dockerfile_dir = File.join(context.dockerfiles_path, context.dockerfile_name) temp_chef_repo = File.join(dockerfile_dir, 'chef') user_chef_repo = File.join(context.dockerfiles_path, '..') ## # Initial Setup # # Create Dockerfile directory (REPO/NAME) directory dockerfile_di...
require "test_helper" describe Review do let(:review) { Review.new(rating: "1", description: "this is great", product: Product.new) } it "must be valid" do expect(review.valid?).must_equal true end describe "relations" do it "must respond to product" do expect(review).must_respond_to :product ...
class Product < ActiveRecord::Base validates_presence_of :title, :description, :price, :image_url validates_numericality_of :price, :greater_than => 0.01 validates_numericality_of :projection, :greater_than => 0 validates_uniqueness_of :title validates_format_of :image_url, :with => %r{\.(gif|jpg|pn...
# frozen_string_literal: true require 'coderay' module ApplicationHelper def page_title if content_for?(:title) content_for(:title) else 'Yay Me!' end end def bootstrap_flash_class(type) case type when 'alert', 'warning' then 'warning' when 'error' then 'danger' when 'no...
require 'rails_helper' describe 'POST /api/v1/sessions' do it 'returns a JSON response with an api_key' do user = create(:user) user_params = { email: "whatever@example.com", password: "password", } post "/api/v1/sessions", params: user_params ...
require 'spec_helper' describe PartnerAppSessionsController do describe 'post' do render_views let(:app) { FactoryGirl.create :recording_app } let(:delight_version) { '2' } let(:app_version) { '1.4' } let(:app_build) { 'KJKJ'} let(:app_locale) { 'en-US' } let(:app_connectivity) { 'wifi' }...
require 'rps_limit' class RpsLock attr_reader :rps def self.lock(test_run_id) res = App.wapi.request( '/v1/rps_lock', { test_run_id: test_run_id }, format: :json, method: :post ) res['body']['secret'] ? self.new(res['body']) : RpsLimit::SessionLock.new(res['body']['rps']) res...
# frozen_string_literal: true class AddQuantityToHolds < ActiveRecord::Migration[4.2] def change add_column :holds, :quantity, :integer, :default => 1 end end
class Hello def hi 'hi' end def hello(name) "hello, #{name}" end protected def protected_hello 'protected_hello' end private def private_hello 'private_hello' end end hello = Hello.new # sendは引数にとったシンボルと同名のメソッドをレシーバーのオブジェクトに置いて実施 hello.send :hi # => "hi" hello.send :hello,'Yoko'...
module Fog module Google class SQL ## # Deletes the backup taken by a backup run. # # @see https://cloud.google.com/sql/docs/mysql/admin-api/v1beta4/backupRuns/delete class Real def delete_backup_run(instance_id, backup_run_id) @sql.delete_backup_run(@project, insta...
require 'is/area' require 'is/point' class Is class << self def point(point) Point.new *point end def all_points(points) pts = points.clone pts.define_singleton_method :in?, ->(area) do area = Area.new area all? { |point| Is.point(point).in? area } end p...
class SpacecatsController < ApplicationController def index @spacecats = Spacecat.all respond_to do |format| format.json { render :json => @spacecats } end end end
require File.join(File.dirname(__FILE__), 'spec_helper') describe "Workfiles" do let(:workspace) { workspaces(:public) } describe "add a workfile" do it "creates a simple workfile" do login(users(:admin)) visit("#/workspaces/#{workspace.id}") wait_for_ajax click_link "Work Files" ...
require 'spec_helper' describe Immutable::Vector do describe '#delete_at' do let(:vector) { V[1,2,3,4,5] } it 'removes the element at the specified index' do vector.delete_at(0).should eql(V[2,3,4,5]) vector.delete_at(2).should eql(V[1,2,4,5]) vector.delete_at(-1).should eql(V[1,2,3,4]) ...
# encoding: utf-8 require 'gli' require 'erubis' require 'fileutils' require 'kckstrt/version' require 'highline/import' require 'ext/string' module Kckstrt extend GLI::App program_desc 'Sinatra app generator' version Kckstrt::VERSION desc 'Generate an app' command :generate do |c| c.desc 'Force gener...
VCR.configure do |config| config.cassette_library_dir = 'test/vcr_cassettes' config.hook_into :webmock config.ignore_localhost = true driver_hosts = Webdrivers::Common.subclasses.map { |driver| URI(driver.base_url).host } driver_hosts += ['googleapis.com'] config.ignore_hosts(*driver_hosts) end
class MyValidator < ActiveModel::Validator def validate(menu) unless menu.url.starts_with? 'http' if menu.url.present? menu.errors[:url] << ' must start with http.' else menu.errors[:url] << ' must be filled in' end end if /\s/.match(menu.url) menu.errors[:url] <...
require 'rails_helper' RSpec.describe User, :type => :model do before do @u = User.new(name: "Edde", email: "YangShuai@gmail.com", password: "fuck you") end subject {@u} it {is_expected.to respond_to :name} it {is_expected.to respond_to :email} it {is_expected.to respond_to :password_digest} it {is_expecte...
require 'securerandom' require_relative 'password_hash' require_relative 'controller' require_relative 'exceptions' require_relative 'schema' require_relative 'sql' require_relative 'auth-helpers' module Controller class User < Base def initialize(current_user, current_key, params, db) super(current_user, ...
class DataPlugins::Facet::V1::FacetItemsController < Api::V1::BaseController include HasLinkedOwners skip_before_action :find_objects, except: [:index, :show] before_action :find_facet, only: [:index, :create] before_action :find_facet_item, except: [:index, :create, :get_linked_facet_items, :link_facet_items...
require 'wallarm/api' require 'wallarm/common/processor' class ExportAttacksProcessor < Processor def initialize( queue, config) super @queue = queue @api_chunk = config.api_chunk || 10 @wapi = Wallarm::API.new( config.api) end def process loop do tuples = @queue.receive_for_export( ...
RSpec.describe PagesController, "#show" do render_views %w[accessibility_statement cookie_statement privacy_policy terms_of_service].each do |page| context "GET /pages/#{page}" do subject { get :show, params: {id: page} } it { should have_http_status(:ok) } it { should render_template(page) ...
require_relative 'helper' require 'Date' class AboutActiveRecord < MiniTest::Test describe "Authors" do describe "validations" do before do @author = Author.new @author.valid? end it "should validate the name" do @author.errors[:name].must_include "can't be blank" ...
require 'spec_helper' require 'deliveryboy/maildir' require 'deliveryboy/plugins/archive' class AuditLog attr_accessor :logs def initialize @logs = [] end def method_missing(method, *args) @logs << [method, args] end end describe Deliveryboy::Plugins::Archive do before(:each) do Deliveryboy::L...
class AddOfferPriceLabelToProperties < ActiveRecord::Migration def change add_column :properties, :offer_price_label, :string end end
class Country < ApplicationRecord has_many :appellations has_many :producers, :through => :appellations end
class RemoveNumberUniququeToCourse < ActiveRecord::Migration def change change_column :courses, :number, :string, unique: false end end
require "test_helper" describe Supergroups::Transparency do include RummagerHelpers let(:taxon_id) { "12345" } let(:transparency_supergroup) { Supergroups::Transparency.new } describe "#document_list" do it "returns a document list for the transparency supergroup" do MostRecentContent.any_instance ...
#!/usr/bin/env ruby require_relative '../etc/apt-get-helper/apt-get-helper' # Find all packages matching the keyword given class AptGetSearch include AptGetHelper def initialize(keyword) @search_list = search(keyword) end def search(keyword) raw = `apt-cache search #{keyword}` results = [] ra...
class Conversation < ApplicationRecord belongs_to :sender, class_name: 'User' belongs_to :receiver, class_name: 'User' has_many :messages, dependent: :destroy validates :sender_id, uniqueness: { scope: :receiver_id } scope :previously_created, lambda { |current_user| where('se...
class LinkedList attr_reader :head, :last def initialize @head = nil @last = nil end def add_node(word, definition) new_node = Node.new(word, definition, nil) if @head.nil? add_first_node(new_node) else @last.next = new_node @last = new_node end end def insert_n...
# https://docs.hetzner.cloud/#resources-actions-get module Fog module Hetznercloud class Compute class Action < Fog::Model identity :id attribute :command attribute :status attribute :progress attribute :started attribute :finished attribute :resource...
class AddShippingStatusToCart < ActiveRecord::Migration def change add_column :carts, :shipping_boolean, :boolean, default: true end end
# -*- mode: ruby -*- # vi: set ft=ruby : # # Vargrantfile to install Jekyll on Debian Jessie # 2016-08 # https://github.com/doka/jekyll-vagrant # doka@wepoca.net # install jekyll $script = <<SCRIPT #--------------------------- # Set variables here! # # 1. Name of the blog export BLOGNAME=myblog # 2. Jekyll versions ...
module Ahoy module Views module Views extend ActiveSupport::Concern module ClassMethods def ahoy_views before_create :process_view belongs_to :visitor, polymorphic: true, optional: true belongs_to :visite...
Letting::Application.routes.draw do get 'arrears/index' resources :sessions, only: %i[create destroy] get 'login', to: 'sessions#new', as: 'login' get 'logout', to: 'sessions#destroy', as: 'logout' get '/404', to: 'errors#not_found' get '/422', to: 'errors#server_error' get '/500', to: 'errors#server_err...
class ChangeTmpgImpressionsToBanner < ActiveRecord::Migration def change rename_table :tmpg_impressions, :banner end end
#!/usr/bin/env ruby # frozen_string_literal: true require 'bundler/inline' gemfile(true) do gem 'translations-manager', git: 'https://github.com/gschlager/translations-manager.git' end require 'translations_manager' require "translations_manager/duplicate_remover" require 'yaml' YML_DIRS = ['../../config/locales'...
=begin rdoc -------------------------------------------------------------------------------- Summarize the ingest times. For each 100 files (or 500 or 1000), figure the average ingest time. Output as a CSV file, like this: "/the/full/ingest_timings_file/path", 100 "Files", "Average time" "1-100", 14.2 "101-...
require 'spec_helper' describe MemosHelper do before { @memo = Memo.new(name: "A3", hints: "", word_list: "ABC", health_decay: Time.now - 10.days, num_practices: 15) } describe "health" do it "calculates the amount of health based on date of last revision" do helper.health(@memo).should == 70 end it "sh...
require 'test_helper' class OrderTest < ActiveSupport::TestCase test "items associate to orders" do w1 = orders(:kyle_week1) assert_equal 1, w1.order_items.count w2 = orders(:kyle_week2) assert_equal 2, w2.order_items.count item_names = w2.order_items.map(&:item).map(&:name) assert_includes...
module Osc class Argument attr_accessor :val def initialize(val) @val = val end private # うーん def padding(s) s + ("\000" * ((4 - (s.size % 4)) % 4)) end end # # valに対し型に応じたエンコードを提供するクラスたち # ここが核。ここでOSCメッセージをエンコードする。 # 見てみるとつまり、packとforce_encodingを行うということであった # ...
require "application_system_test_case" class VictimsTest < ApplicationSystemTestCase setup do @victim = victims(:one) end test "visiting the index" do visit victims_url assert_selector "h1", text: "Victims" end test "creating a Victim" do visit victims_url click_on "New Victim" fil...
module Scm module Workflow end end module Scm::Workflow class ConfigElement attr_reader :info; attr_accessor :value; attr_reader :hideinput; def initialize (info, hideinput, default) @info = info; @hideinput = hideinput; @value = default; end end class Flow a...
class Scheme < ApplicationRecord has_many :scheme_needs has_many :needs, through: :scheme_needs end
# frozen_string_literal: true # rubocop:todo all require 'lite_spec_helper' describe Mongo::Operation::Find::Builder::Flags do describe '.map_flags' do shared_examples_for 'a flag mapper' do let(:flags) do described_class.map_flags(options) end it 'maps allow partial results' do ...
class UsuarioSitiosController < ApplicationController before_action :set_usuario_sitio, only: [:show, :edit, :update, :destroy] # GET /usuario_sitios # GET /usuario_sitios.json def index @usuario_sitios = UsuarioSitio.all end # GET /usuario_sitios/1 # GET /usuario_sitios/1.json def show...
require 'helper' require 'capybara' require 'capybara/dsl' require 'capybara/webkit' Capybara.default_selector = :css Capybara.default_driver = :webkit Capybara.javascript_driver = :webkit class GpkureAcceptanceTest < Test::Unit::TestCase include Capybara::DSL def setup Capybara.app = Sinatra::Applicatio...
class ActivityMigrator < AbstractMigrator class << self def prerequisites(options) DatabaseObjectMigrator.migrate ChorusViewMigrator.migrate WorkspaceMigrator.migrate WorkfileMigrator.migrate(options) SandboxMigrator.migrate #workaround for broken composite keys in DATASET_IMPORT act...
# === COPYRIGHT: # Copyright (c) Jason Adam Young # === LICENSE: # see LICENSE file class NotifyDraftPickChannel < ApplicationCable::Channel def subscribed stream_from 'draft_pick_updates' end end
class AddIndexToWorkgroupMemberships < ActiveRecord::Migration def self.up add_index "workgroup_memberships", :sail_user_id add_index "workgroup_memberships", :workgroup_id end def self.down remove_index "workgroup_memberships", :sail_user_id remove_index "workgroup_memberships", :workgroup_id ...
require 'rails_helper' describe Meter do let!(:audit_strc_type) { create(:meter_audit_strc_type) } it { should have_many :audit_structures } describe '.audit_strc_type' do it 'retrieves the structure_type for meters' do expect(Meter.audit_strc_type).to eq audit_strc_type end end describe '.n...
module Orocos::Async::Log class OutputReader < Orocos::Async::ObjectBase extend Utilrb::EventLoop::Forwardable extend Orocos::Async::ObjectBase::Periodic::ClassMethods include Orocos::Async::ObjectBase::Periodic self.default_period = 0.1 attr_reader :policy attr_rea...
require 'cubic/redis_connection/pool' module Cubic module Providers class Redis DEFAULT_URL = "redis://localhost:6379/15".freeze SANITIZED_REGEX = /[^A-Za-z0-9|\.|\_|:|-]/ attr_reader :pool # Initializes a new instance of +Cubic::Providers::Redis+ # # config - the hash pas...
class SeoInfo < ActiveRecord::Base belongs_to :seo_object, :polymorphic => true validates_presence_of :seo_object_id validates_presence_of :seo_object_type validates_presence_of :cobrand_id # puts double-quotes around the content of these fields so they can be eval'd %w(meta_description meta_keyword...
class CreateItemVenta < ActiveRecord::Migration def change create_table :item_venta do |t| t.belongs_to :venta, index: true t.belongs_to :producto, index: true t.integer :cantidad t.float :precio_unitario t.timestamps null: false end end end
require "minitest_helper" require "airbrussh/colors" class Airbrussh::ColorsTest < Minitest::Test include Airbrussh::Colors def test_red assert_equal("\e[0;31;49mhello\e[0m", red("hello")) end def test_green assert_equal("\e[0;32;49mhello\e[0m", green("hello")) end def test_yellow assert_equ...
#=============================================================================== # ** Window_KeyHelp #------------------------------------------------------------------------------- # Finestra generica che mostra i comandi del menu. Viene chiamata dalle # schermate Status, Skills, Equip ecc... #========================...
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'test_helper.rb')) class VmInitializationTest < Test::Unit::TestCase include KoiVMRuby test "VM.new without arguments should return default state" do vm = VM.new default_state = { :opcodes => [], :globals => {}, :fiber =...
class AddStatusToAttendance < ActiveRecord::Migration[6.0] def change add_column :attendances, :status, :boolean end end
require 'ohol-family-trees/maplog_file' module OHOLFamilyTrees module MaplogCache class Servers include Enumerable def initialize(cache = "cache/publicMapChangeData/") @cache = cache end attr_reader :cache def each(&block) iter = Dir.foreach(cache) .sele...
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception def authenticate if !signed_in? redirect_to new_session_path end end def signed_in? current_user.signed_in...
class Disease < ActiveRecord::Base has_many :diagnoses, dependent: :destroy end
class Message < ApplicationRecord belongs_to :user belongs_to :conversation after_create_commit :prepare_for_broadcast def prepare_for_broadcast conv = self.conversation if conv.recipient.presence == "offline" conv.recipient_offline elsif conv.sender == "offline" conv.sender_offline ...
# frozen_string_literal: true RSpec.describe Dor::Services::Client::ReleaseTags do before do Dor::Services::Client.configure(url: 'https://dor-services.example.com', token: '123') end let(:connection) { Dor::Services::Client.instance.send(:connection) } let(:pid) { 'druid:123' } subject(:client) { desc...
# == Schema Information # # Table name: rounds # # id :integer not null, primary key # name :string # deadline_time :datetime # finished :boolean # data_checked :boolean # deadline_time_epoch :integer # deadline_...
class DrupalUsers < ActiveRecord::Base attr_accessible :title, :body, :name, :pass, :mail, :mode, :sort, :threshold, :theme, :signature, :signature_format, :created, :access, :login, :status, :timezone, :language, :picture, :init, :data, :timezone_id, :timezone_name self.table_name = 'users' self.primary_key = '...
require 'rails_helper' describe Deck do let (:deck) { create(:deck) } it { should validate_presence_of(:user) } it { should validate_presence_of(:name) } it 'can be checked if default?' do expect(deck.default?).to be false end it 'can be set as default' do deck.set_default! expect(deck.defa...
# Copyright (c) 2006, 2007 Ruffdogs Software, Inc. # # This program 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 Foundation; either version 2 of the License. # # This program is distributed in the hope that it will be ...
task :default => [:build] desc "Launch preview environment" task :preview do system "jekyll --no-server" end desc "Build site" task :build do |task, args| system "jekyll --no-auto" end desc "Package app for production" task :package do ENV['JEKYLL_ENV'] = 'production' ENV['VERSION_style'] = %x{git log -p ...
# frozen_string_literal: true require 'stannum/contracts/map_contract' require 'support/examples/constraint_examples' require 'support/examples/contract_builder_examples' require 'support/examples/contract_examples' RSpec.describe Stannum::Contracts::MapContract do include Spec::Support::Examples::ConstraintExampl...
# Service for dealing with stripe calls class StripeService def initialize(options = {}) @customer_id = options.fetch(:customer_id, 'cus_CHdv4NciT0Y1MA') @name = options.fetch(:name, 'Joe Public') @address = options.fetch(:address, fake_address) @items = options.fetch(:items, fake_items) end def ...
module Models class Transaction attr_accessor :item attr_accessor :destination, :amount # all required data def initialize(item:, destination:, amount:) @item = item @destination = destination @amount = amount end def to_hash { who: destination, type: ...
class User include MongoMapper::Document include Canable::Cans key :email, String key :name, String key :groups, Array key :password, String key :password_confirmation, String def admin? groups.include?('website administrator') end end
class CommentsController < ApplicationController before_action :comment, only: [:edit, :update, :destroy] before_action :check_admin, only: [:edit, :update, :destroy] def create @comment = Comment.new(perm_params) @comment.article_id = params[:article_id] @comment.user = current_user if @comment....
class Book < ActiveRecord::Base belongs_to :category, :counter_cache => true validates :name, presence: true validates :author, presence: true validates :year, presence: true end