text
stringlengths
10
2.61M
# frozen_string_literal: true require 'swagger_helper' describe 'Content' do path '/content/show' do get 'Retorna as informações do sistema' do tags 'Content' description 'Modelo de documentação para APIs contendo as informações da rota' consumes 'application/json' response '200', 'blog...
class CoursesController < ApplicationController before_action :authenticate_user!, :except => [:index, :show, :apply, :applycreate] before_action :authenticate_client!, :only => [:apply, :applycreate] def index if user_signed_in? @courses = Course.where(user_id: current_user.id) ...
# time of day can be represented as the number of minutes before # or after midnight # if number is positive, time is after midnight # if negative, time is before midnight # write a method that takes a time using this minute-based format # and returns the time of day in 24 hour format # method should work with any int...
# frozen_string_literal: true class ViewsHelperTest < ActionView::TestCase test "overlay_icon should return for kml" do layer = layers(:kml) assert_dom_equal %{<i class="fa fa-fw fa-circle" style="color: rgba(255,0,0,0.8)"></i>}, overlay_icon(layer) end test "overlay_icon should return for geojson" do ...
require 'test_helper' class EventSaverTest < ActiveSupport::TestCase setup do @group_event = group_events(:brazil_trip) end test "#create a draft with a small dataset" do saver = EventSaver.new({name: "test", group_event_id: @group_event.id}).create saved, event = saver.first, saver.second asse...
class CowsController < ApplicationController before_action :set_cow, only: [:show, :edit, :update, :destroy] def index @cows = Cow.all end def show end def new @cow = Cow.new end def edit end def create @cow = Cow.new(cow_params) respond_to do |format| if @cow.save ...
require 'rails_helper' RSpec.describe User, type: :model do describe "#validations" do it 'should have valid factory' do user = build :user expect(user).to be_valid end it 'should validate presence of attributes' do user = build :user, login: nil, provider: nil expect(user).not_...
# coding: utf-8 class Lyric < ActiveRecord::Base has_many :lines belongs_to :artist attr_accessible :text, :title validates :title, presence: { message: "Необходимо указать название трека." }, length: { minumum: 1, maximum: 120, ...
class Fixnum def to_english self.to_eng.join(" ") end def to_eng(digit = 0) return [] if self == 0 if digit % 3 == 0 last_two = self % 100 beginning = (self / 100).to_eng(digit + 2) mid = if last_two > 19 last_one = last_two % 10 last_two -= last_one last_tw...
require 'rails_helper' RSpec.describe BoardsGroup, :type => :model do describe 'validations' do it 'validates not null and uniqueness of name and does not throw a db error' do boards_group = FactoryGirl.create(:boards_group) expect(FactoryGirl.build(:boards_group, id: boards_group.id, name: nil)).not_to be_...
require "spec_helper" RSpec.describe TwitterBro::Client do let(:consumer_key) { "le consumer key" } let(:consumer_secret_key) { "le consumer secret key" } let(:client) do described_class.new consumer_key: consumer_key, consumer_secret_key: consumer_secret_key end subject { client } its(:consumer_key...
# frozen_string_literal: true module FileReaderTest module EachByte def test_each_byte file = file_containing("weweia") bytes = [] file.each_byte do |byte| bytes << byte end assert_equal [0x77, 0x65, 0x77, 0x65, 0x69, 0x61], bytes end def test_each_byte_increments...
ActiveAdmin.register MenuItem do menu parent: "Navigation" include ActiveAdmin::SortableTable # creates the controller action which handles the sorting config.sort_order = 'position_asc' # assumes you are using 'position' for your acts_as_list column index do panel 'How Menu Items work!' do 'Menu it...
require "cemetry/version" require "miserable" require "osc-ruby" require "noone" module Cemetry class Sequence attr_reader :bpm_msec def initialize(bpm) @bpm_msec = Miserable.new(bpm) end def play(proc, only_once: nil) begin osc_client = OSC::Client.new("localhost", 2345) ...
class ErrorSerializer < ActiveModel::Serializer attributes :error, :links def error { message: object[:message], code: object[:code] } end def links object[:links] || {} end end
Rails.application.routes.draw do scope :api, defaults: { format: :json } do devise_for :users, :controllers => {sessions: 'api/sessions', registrations: 'api/registrations'} post 'reset_password', to: 'api/resets_passwords#reset' end namespace :api, defaults: { format: :json } do resources :memorial_...
# encoding: utf-8 module Werdau class CsvProductImporter @queue = :high def self.import(file_path) file = File.open(File.realpath(file_path), 'r') status = Spree::ImportStatus.active.last taxonomy = Spree::Taxonomy.find_by_name('Категории') path2taxon = {} taxonomy.t...
module AbsoluteRenamer # The main Error class, all Exception classes inherit from this class. class Error < StandardError; end # Raised when the renaming mode is not a known one class RenamingModeUnknown < Error; end require 'absolute_renamer/plugin_loader' require 'absolute_renamer/renamer' require 'ab...
# frozen_string_literal: true # super piece class class Piece attr_accessor :moves, :last_move def initialize(moves, last_move, moved) @moves = moves @last_move = [] @moved = false end def name name end def a_piece? name != String end end
class RecipeRelate < ApplicationRecord belongs_to :relater, foreign_key: "relater_id", class_name: "Recipe" belongs_to :relatee, foreign_key: "relatee_id", class_name: "Recipe" validates :relater, uniqueness: { scope: :relatee } end
module Sikulio class RelativeElement < Element attr_accessor :offset_x attr_accessor :offset_y # Sets screen and image file path def initialize(screen, ident, offset_x, offset_y) self.offset_x = offset_x self.offset_y = offset_y super screen, ident end # Click...
# # Be sure to run `pod lib lint CS-Aviasales.podspec' to ensure this is a # valid spec before submitting. # # Any lines starting with a # are optional, but their use is encouraged # To learn more about a Podspec see https://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.name = 'CS-Avi...
# ============================================================================ # # Prime number thread # # ============================================================================ # # Author: J.-M. Hufflen # Date: February 2015 # # ===========================================================...
class WarPlayerSerializer < ActiveModel::Serializer attributes :id, :position, :friendly, :war_id has_one :player, embed: :ids, embed_in_root: true has_many :attack_logs, embed: :ids, embed_in_root: true def attack_logs object.attacks + object.defenses end end
class BookingClient < ChannelClientBase require 'rest-client' @@username = APP_CONFIG['booking_user'] @@password = APP_CONFIG['booking_password'] def get_all_rooms(hotel_id) @service_url = APP_CONFIG['booking_base_uri'] + '/hotels/xml/rooms' @request = { username: @@username, pas...
#!/usr/bin/env ruby require "yaml" # Save a config file at ~/.projects with something like # # project_name: # home: ~/Sites/some_project # tabs: # - rails server thin # - rails console # - redis-server # - mongod --dbpath=tmp/mongodb # # To open all tabs for this project, just run # ...
class User < ActiveRecord::Base validates :first_name, :last_name, :email, presence: true validates :email, format: { with: /\A[^@]+@([^@\.]+\.)+[^@\.]+\z/ } has_one :trainer has_many :sessions def self.find_by_credentials(email, password) user = User.find_by_email(email) user && user.is_password?(pas...
module Backup module Environment module UnixConfiguration require 'active_record' # Sets BACKUP_PATH BACKUP_PATH = ENV['BACKUP_PATH'] || "/opt/backup" # Sets DB_CONNECTION_SETTINGS DB_CONNECTION_SETTINGS = { :adapter => "sqlite3", :database => "#...
class Survivor < ActiveRecord::Base mount_uploader :picture, PictureUploader belongs_to :city def city_name city.name if city end end
module SerializableModel extend ActiveSupport::Concern def serialize_row!(columns) columns.push(:id) row = build_row(columns) { "data": { "id": row[:id].to_s, "type": self.class.name.downcase, "attributes": row } } end def build_row(columns) row = {} ...
# addawstags.rb # # Description: Look for instance tags in EC2 and tag CFME VM # begin def log(msg) log(:info, msg, false) end def log(level, message, update_message=false) $evm.log(level, "#{@method} - #{message}") if update_message case $evm.root['vmdb_object_type'] when 'miq_provisio...
class SlogsController < ApplicationController def index @slogs = Slog.all # respond_to do |format| # format.html { render :index } # format.json { render json: @slogs, status: :ok } # end end def new @slog = Slog.new end def show @slog =...
# coding: utf-8 require 'spec_helper' feature 'News releases' do before do user = create(:user) sign_in(user) visit root_path click_link 'News' end # ユーザーとして context 'as a user' do # ニュースリリースを追加する scenario 'adds a news release' do expect(page).to_not have_content 'BigCo switches...
class CreateRelationshipTable < ActiveRecord::Migration[5.2] def change create_table :relationships do |t| t.integer :player_id t.integer :town_id t.integer :bounty t.boolean :thanehood t.integer :goodwill t.boolean :home end end end
class Location < ActiveRecord::Base belongs_to :user scope :with_user, -> (user) { where(user: user) if user.present? } scope :with_coordinates, -> (lat, lon){ where(latitude: lat, longitude: lon) } def self.from_current(position) with_coordinates(position.latitude, position.longitude). first_or_ini...
class RenameExpireToExpiresAtInKeys < ActiveRecord::Migration def self.up rename_column :keys, :expire, :expires_at end def self.down rename_column :keys, :expires_at, :expire end end
require_relative 'test_helper' context "Lightswitch::Actions" do context "#get_scheduled_state_changes" do setup { schedules = Lightswitch::Schedules.new schedules.create_schedule_collection({ name: 'test', ...
module MDB class UsersController < MDBController load_resource except: [:show, :edit, :update] before_filter :load_user, :only => [:show, :edit, :update] authorize_resource respond_to :html, :json, :xml # GET /users # GET /users.json def index unless params[:name].presen...
class Person < ActiveRecord::Base has_many :curations, dependent: :destroy has_many :users, through: :curations accepts_nested_attributes_for :curations has_many :photos, dependent: :destroy has_many :transactions, dependent: :destroy has_many :connections, dependent: :destroy has_many :posts, through: :...
VAGRANT_API_VERSION = "2" Vagrant.configure(VAGRANT_API_VERSION) do |config| config.vagrant.plugins = "vagrant-disksize" config.vm.box = "ubuntu/bionic64" config.disksize.size = '50GB' config.vm.provider "virtualbox" do |vb| vb.name = "Developer machine" vb.cpus = 2...
class Business attr_reader :name, :address, :phone, :rating_img, :review_snippet , :yelp_page, :img_url, :coord def initialize(biz_burst) @name = biz_burst.name @address = biz_burst.location.address.first @phone = biz_burst.display_phone @rating_img = biz_burst.rating_img_url_large @review_snip...
コード例 buy_tickets("Sam", "Dave", "David") buy_tickets("John", "Paul", "Ringo", "George") 出力例 Buying a ticket for Sam. Buying a ticket for Dave. Buying a ticket for David. Buying a group ticket for John, Paul, Ringo, George. # 可変長引数 # *をつければ引数を、配列に指定できる。 # めそっどには一つの引数の定義で、複数の引数を設定でき、配列として結果を返す。 # これを可変長引数という。 def buy...
require File.dirname(__FILE__) + '/../../../spec_helper' describe 'Fog::AWS::S3::Owner' do describe "#initialize" do it "should remap attributes from parser" do owner = Fog::AWS::S3::Owner.new( 'DisplayName' => 'name', 'ID' => 'id' ) owner.display_name.should == 'name...
class CopyFileDelegate attr_accessor :copy_to_text_field attr_accessor :parent, :copy_file_window def initialize @file_controller = FileController.new end def submit_copy_file_window(sender) @parent.queue.async do destination = @copy_to_text_field.stringValue @file_controller.copy(@files_to_copy, desti...
module CamaleonCms class PostCommentDecorator < Draper::Decorator delegate_all # return created at date formatted def the_created_at(format = :long) h.l(object.created_at, format: format.to_sym) end # return owner of this comment def the_user object.user.decorate end alia...
class CreateCountrypictures < ActiveRecord::Migration def change create_table :countrypictures do |t| t.references :country t.timestamps end add_index :countrypictures, :country_id end end
class SaveRowIsComplete prepend SimpleCommand def initialize(row) @row = row end def call @row.wz_shelves_count = get_shelves_count(@row.shelves) @row.has_shelves = true if @row.wz_shelves_count > 1 @row.wz_trays_count = get_trays_count(@row.shelves) @row.has_trays = true if @row.wz_trays_...
module Bundle class BrewInstaller def self.install(name, options = {}) result = new(name, options).install_or_upgrade result = BrewServices.restart(name) if result && options[:restart_service] result end def initialize(name, options = {}) if Bundle.brew_installed? @full_na...
class ActiveRecord::Base self.primary_key = :uuid #connection.raw_connection.recv_timeout = 10 #connection.raw_connection.send_timeout = 5 before_create :assign_uuid def assign_uuid if attributes.include?('uuid') self.uuid = UUID.new.generate(:compact) if uuid.blank? end end def self.conn...
require "application_system_test_case" class BookHistoriesTest < ApplicationSystemTestCase setup do @book_history = book_histories(:one) end test "visiting the index" do visit book_histories_url assert_selector "h1", text: "Book Histories" end test "creating a Book history" do visit book_hi...
require 'rails_helper' RSpec.describe Comment do describe '#create' do it "is invalid without a user_id" do comment = build(:comment, user_id: nil) comment.valid? expect(comment).to_not be_valid end it "is invalid without a product_id" do comment = build(:comment, product_id: ni...
# # Cookbook Name:: jruby # Recipe:: default # # Copyright 2015, YOUR_COMPANY_NAME # # All rights reserved - Do Not Redistribute # JRUBY_VERSION='9.2.0.0' JRUBY_FILE="jruby-dist-#{JRUBY_VERSION}-bin.tar.gz" JRUBY_FILE_PATH="/tmp/#{JRUBY_FILE}" JRUBY_URL="https://repo1.maven.org/maven2/org/jruby/jruby-dist/#{JRUBY_VERS...
require 'test_helper' class CauseCategoriesControllerTest < ActionController::TestCase setup do @cause_category = cause_categories(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:cause_categories) end test "should get new" do get :new ...
require 'rails_helper' RSpec.describe Sushi, type: :model do it 'contains Rice and Wasabi' do FactoryGirl.create(:user) expect(FactoryGirl.create(:sushi).ingredients).to eq('Rice and Wasabi') end it 'contains mystery fish' do sushi = FactoryGirl.create(:sushi, ingredients: 'Mystery Fish') expect...
# Ruby code for reduce.rb @validation_array = [] @fieldgrabber = false md5 = nil FIELDGRABBER_PAYLOAD = '0' def store_row(value) if value == FIELDGRABBER_PAYLOAD warn "setting fieldgrabber true" @fieldgrabber = true else warn "adding row to storage" @validation_array.push(valu...
require 'spec_helper' require_relative '../exercises/string_exercises' RSpec.describe 'String Exercises' do describe 'concatenation exercise' do it 'returns "hello world!"' do expect(concatenation_exercise('world')).to eq('Hello world!') end xit 'returns "hello universe!"' do expect(concat...
require 'test_helper' class VoteTest < ActiveSupport::TestCase # test "the truth" do # assert true # end def setup @vote1 = votes(:one) @vote2 = votes(:two) @vote3 = votes(:three) @vote4 = votes(:four) end def teardown @vote1 = nil @vote2 = nil @vote3 = nil @vote4 = nil ...
require_relative '../../test_helper' class MomentumCms::BlockTest < ActiveSupport::TestCase def setup I18n.enforce_available_locales = false I18n.locale = :en end def test_fixture_validity MomentumCms::Block.all.each do |block| assert block.valid? end end def test_belongs_to_page ...
Rails.application.routes.draw do # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html get '/(:order)', to: 'application#index', as: :root resources :starred, only: [:update, :destroy] end
class PartyPlacesController < ApplicationController def show @party_place = PartyPlace.find(params[:id]) @reservation = Reservation.new @user = current_user end def index if params[:query].present? sql_query = <<~SQL party_places.name @@ :query OR party_places.address @@ :qu...
require 'filmbuff' module Cinch module Plugins class IMDb include Cinch::Plugin def initialize(*args) super @imdb = FilmBuff::IMDb.new @imdb.locale = config[:locale] if config[:locale] end match /imdb (.+)/i def execute(m, title) movie = @imdb.find...
class ProjectSerializer include FastJsonapi::ObjectSerializer attributes :name, :department, :desc, :budget, :end_destination, :quantity, :client_id, :user_id, :target_completion_date, :completion_date, :created_at, :updated_at attribute :comments do |project| project.comments.map do |comment| ...
class CreateReviews < ActiveRecord::Migration[5.1] def change create_table :reviews do |t| t.integer :balance t.integer :benefits t.integer :advancement t.integer :management t.integer :culture t.decimal :average t.integer :question1 t.integer :question2 t.int...
class Label < ActiveRecord::Base has_many :optionvalue_labels has_many :option_values ,through: :optionvalue_labels end
require "linguist" require_relative "ruby_tracer" require_relative "c_syntax_tracer" require_relative "python_tracer" class VirtualBlob < Linguist::FileBlob def initialize(path, data) @path = path @data = data end def data @data end def size @size ||= data.length end end class Tracer ...
class RatingsController < ApplicationController def create @app = App.find(params[:app_id]) @rating = @app.ratings.create(rating_params) redirect_to app_path(@app) end private def rating_params params.require(:rating).permit(:comment) end end
class BarcodesController < ApplicationController before_action :set_barcode, only: [:show, :edit, :update, :destroy] # GET /barcodes # GET /barcodes.json def index @barcodes = Barcode.all end def scan if params[:barcode].present? @barcode = Barcode.find_by_uuid(params[:barcode]) if params[:b...
require 'rubygems' require 'nokogiri' require 'tempfile' require 'digest/md5' module BrowsingSupport class VoiceSynthesis attr_accessor :open_jtalk attr_accessor :open_jtalk_options attr_accessor :lame attr_accessor :lame_options attr_accessor :max_part_length attr_accessor :logger def i...
class JobPost < ActiveRecord::Base belongs_to :location belongs_to :category belongs_to :company has_many :applicant_job_posts has_many :applicants,:through=>:applicant_job_posts attr_accessible :category_id, :company_id, :job_post_basic_salary, :job_type,:job_post_description, :job_post_end_date, :job_post...
class Grepples < Formula desc "Aggressively-parallelized grep utility for AWS S3" homepage "https://github.com/jsleeio/grepples" url "https://github.com/jsleeio/grepples.git", :using => :git, :tag => "v0.1.2", :revision => "ec3d3d474c7ad0581e56fcfd6ff207d008c6b061" head "https://github...
require 'spec_helper' describe HelloTxt::Client, "with expected results" do before(:each) do @client = HelloTxt::Client.new('a','b') @params = {'app_key' => 'a', 'user_key' => 'b'} end it "should validate keys successfully" do init_ok_response 'user.validate' uri = URI.parse "#{HelloTxt::API_...
class Pin < ActiveRecord::Base Paperclip.options[:command_path] = 'C:/Program Files/ImageMagick-6.9.2-Q16' belongs_to :user has_attached_file :image, :styles => { :medium => "300x300>", :thumb => "100x100>" } #do_not_validate_attachment_file_type :image # validates_attachment_content_type :image, ...
class AddAwsCredentialsToUser < ActiveRecord::Migration def change add_column :users, :aws_queue_url, :string, :null => false, :default => '', :after => :dropbox_token_key add_column :users, :aws_vault_id, :string, :null => false, :default => '', :after => :dropbox_token_key add_column :users, :aws_secret...
require 'db/migrations/utils' Sequel.migration do up do create_table(:series_system_rlshp) do primary_key :id Integer :accession_id_0 Integer :accession_id_1 Integer :resource_id_0 Integer :resource_id_1 Integer :archival_object_id_0 Integer :archival_object_id_1 ...
require 'spec_helper' module Api module V1 describe RelationshipsController do render_views let(:homer) { create(:user, name: 'Homer Simpson') } let(:marge) { create(:user, name: 'Marge Simpson') } before do homer.create_api_key marge.create_api_key ...
class StorySweeper < ActionController::Caching::Sweeper observe Content, Comment, Vote def after_save(record) if record.is_a?(Content) story = record elsif record.is_a?(Comment) and record.commentable.is_a?(Content) story = record.commentable elsif record.is_a?(Vote) and record.voteable.is_a...
class CreateMmsEvents < ActiveRecord::Migration def self.up create_table :mms_events do |t| t.string :url, :limit=>255 t.string :name, :limit=>255 t.string :image_url, :limit=>255 t.integer :state, :default=>0, :limit=>1 #活动状态,默认0-未进行,1-进行中,2-已结束 t.datetime :begin_time t.dateti...
class NotificationsController < ApplicationController before_action :authenticate_user! before_action :set_categories before_action :set_item before_action :set_item_search_query before_action :my_notifications private def set_item @item = Item.find_by_id(params[:id]) end def item_params par...
require 'test_helper' if Cell.rails_version >= 3.1 class Song < OpenStruct extend ActiveModel::Naming def persisted? true end def to_param id end end class SongCell < Cell::ViewModel def show render end def title song.title.upcase end def se...
describe ItunesReceiptDecoder::Decode::UnifiedReceipt do shared_context :production do let(:receipt_file) { 'unified_production' } end shared_context :sandbox do let(:receipt_file) { 'unified_sandbox' } end subject { described_class.new(receipt, options) } let(:receipt) do data = File.read( ...
require 'spec_helper' describe Boilerpipe do it 'has a version number' do expect(Boilerpipe::VERSION).not_to be nil end end
# frozen_string_literal: true module MLBStatsAPI module Schedules SCHEDULE_TYPES = { default: '/schedule', postseason: '/schedule/postseason', tied: '/schedule/games/tied', postseason_series: '/schedule/postseason/series', tune_in: '/schedule/postseason/tuneIn' }.freeze def...
class BackfillTweetsWorker include Sidekiq::Worker def perform tweets = TwitterAdapter.tweets(ENV['TWITTER_USERNAME'], max_tweet_id) tweets.each do |tweet| save_tweet(tweet) end end private def save_tweet(tweet) event = Event.create!( external_reference: tweet.id, happene...
module Bottle class Server include Bottle::AMQP attr_accessor :queue_name, :reply_queue_name, :broker def initialize(queue_name=Bottle::DEFAULT_QUEUE_NAME, amqp_settings = {}, options = {}) @options = options @amqp_settings = Bottle::AMQP_DEFAULTS.merge(amqp_settings) @queue_...
require 'test_helper' class MotocicletasControllerTest < ActionController::TestCase setup do @motocicleta = motocicletas(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:motocicletas) end test "should get new" do get :new assert_respon...
class AddAttachmentCapaToLivros < ActiveRecord::Migration[4.2] def change create_table :livros do |t| t.string :titulo, limit: 600 t.string :autores, limit: 600 t.text :sinopse t.timestamps end end
require 'rails_helper' describe User, :type => :model do # To add: # check it only returns the given number of activities # all kinds of sources of activiites (question, answer, following answer, question, etc) # activities are sorted properly # integration - language is correct (You vs. full usernam...
# 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 bin/rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # ...
class CreateCards < ActiveRecord::Migration def up create_table :cards do |t| t.string :description t.string :card_type t.string :card_name t.integer :default_quantity t.integer :opponent_draw_n, default: 0 t.boolean :skip_turn, default: false t.integer :view_top_deck_n, ...
module Api::Public::V1 class BillboardsController < BaseController before_filter :sanitize_id, only: [:show] def index @billboards = Billboard.published respond_with @billboards end #--------------- def show @billboard = Billboard.published.where(id: @id).first if !@bil...
# frozen_string_literal: true class Comment < ApplicationRecord belongs_to :user belongs_to :post validates :body, presence: :true validates_length_of :body, minimum: 5, maximum: 2000 validate :comment_limit, on: :create scope :today, -> { where(created_at: (Time.now.beginning_of_day..Time.now.end_of_d...
require 'test/unit' require 'soap/rpc/driver' require 'soap/rpc/standaloneServer' module SOAP module Fault class TestCustomFault < Test::Unit::TestCase Port = 17171 class CustomFaultServer < SOAP::RPC::StandaloneServer def on_init add_method(self, 'fault', 'msg') end def fault(msg) SOA...
class AddDefaultsToPosts < ActiveRecord::Migration def change change_column :posts, :he_votes, :integer, default: 0 change_column :posts, :she_votes, :integer, default: 0 end end
class DataTree attr_reader :root, :lines def initialize lines @root = Node.new(lines.shift) lines.each do |line| @root.add_child(line) end end end
class Goal < ApplicationRecord def achieved_goal if self.name == "Projetos" Project.this_year_projects.count elsif self.name == "Faturamento" Project.faturamento elsif self.name == "NPS" Project.total_nps else 10 end end 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 rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel...
module PageObjects module Users class NewPage < PageObjects::Document path :new_user path :images # from successful create path :users element :navbar, locator: '.navbar', is: PageObjects::Shared::NavBar form_for :user, locator: '.js-new-users' do element :name elem...
class CsvLinkImport include ActiveModel::Model include ActiveModel::Validations::Callbacks validates :file_path, presence: true, allow_blank: false validate :validate_links attr_accessor :file_path, :create_categories def options @options ||= { remove_unmapped_keys: true, downcase_header:...
class Participant < ActiveRecord::Base ETHNICITY_OPTIONS = ['Hispanic or Latino', 'Not Hispanic or Latino', 'Unknown/Other/Unreported'].freeze RACE_OPTIONS = ['American Indian/Alaska Native', 'Asian', 'Middle Eastern', 'Native Hawaiian or other Pacific Islander', 'Black or African American', 'White', 'Unk...
class AccountsController < ApplicationController before_filter :process_type before_filter :get_organization before_filter :get_account, only: [:show] def create @organization.send(@collection_name).create!(account_params) render nothing: true, status: 201 end def show render json: {account: ...