text
stringlengths
10
2.61M
class Micropost < ActiveRecord::Base attr_accessible :content belongs_to :user validates :content, :presence => true, :length => { :maximum => 140 } validates :user_id, :presence => true default_scope :order => 'microposts.created_at DESC' scope :from_users_followed_by, lambda { |user| followed_by(user) } privat...
module DelegateCached class TargetInstaller < Installer def install_instance_methods install_update_method install_callback unless options[:no_callback] || options[:polymorphic] end def install_update_method @target.model.class_eval %( def #{update_method_name} #{updat...
class ApplicationController < ActionController::Base before_action :current_cart, :current_checkout, :current_customer, :current_seller def current_cart @current_cart ||= Cart.new() end helper_method :current_cart def current_checkout @current_checkout ||= Checkout.new() end helper_method :curr...
module Github class LanguagesRepository include FaradayClient def all(username) repos = get_user_repos(username) return nil, 'languages cannot be fetched' if repos.nil? languages = repos.map { |r| get_languages(username, r['name']) } return nil, 'languages cannot be fetched' unless ...
class Genre < ApplicationRecord has_many :hobbies end
class ChangeIntouchTelegramChatSubscriptionsChatIdType < Rails.version < '5.0' ? ActiveRecord::Migration : ActiveRecord::Migration[[Rails::VERSION::MAJOR, Rails::VERSION::MINOR].join('.')] def change change_column :intouch_telegram_chat_subscriptions, :chat_id, :bigint end end
module Forums class ThreadPresenter < BasePresenter presents :thread def created_by @created_by ||= present(thread.created_by) end def link(options = {}) link_to(thread.title, forums_thread_path(thread), options) end def breadcrumbs crumbs = path_objects.map { |path| conte...
require File.dirname(__FILE__) + '/../../test_helper' class Qa::QuestionPhotoControllerTest < ActionController::TestCase def setup App.stub!(:qa_moderation_enabled, :return => false) @logged_in_user = users(:matt) @uploaded_question_photo = {:uploaded_question_photos => "a,b,c,d"} @session_has...
class Health < ApplicationRecord DAYS_IN_MONTH = [nil, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] belongs_to :baby, inverse_of: :healths validates :weight, presence: true validates :height, presence: true before_save :calculate_age def calculate_age return if baby.blank? borrowed_month = fal...
class Shop < ApplicationRecord validates :shop_name, presence: true has_many :points, foreign_key: :payer_id end
class Target attr_reader :url, :method attr_accessor :resp, :body # resp.body strore the original body, @body store the parsed body def initialize(url_str, query_str, method) @url = url_parse(append_query(url_str, query_str)) @method = method @body = nil end def parse_body(local,localport) ...
require './src/tokenizer/lexer' require './src/tokenizer/errors' require './spec/contexts/lexer' RSpec.describe Tokenizer::Lexer, 'error handling' do include_context 'lexer' describe '#next_token' do it 'raises an error when too much indent' do mock_reader( "インデントしすぎるとは\n" \ "  行頭の空白は 「...
class User < ApplicationRecord # encrypt password has_secure_password validates_presence_of :email, :password_digest validates_email_format_of :email, :message => 'invalid email address' def generate_password_token! self.reset_password_token = generate_token self.reset_password_sent_at = Time.now.ut...
require "digest" class Client < ActiveRecord::Base validates_length_of :username, :within => 3..40 validates_length_of :name, :maximum => 50 validates_length_of :email, :maximum => 50 validates_uniqueness_of :username validates_presence_of :name, :username, :email, :salt, :time_zone validates_format_of :...
# frozen_string_literal: true # == Schema Information # # Table name: post_types # # id :bigint not null, primary key # description_template :text # name :string # created_at :datetime not null # updated_at :datetime not null # user_...
# frozen_string_literal: true require_relative "lib/hb_csv/version" Gem::Specification.new do |spec| spec.name = "hb-csv" spec.version = HBCSV::VERSION spec.platform = Gem::Platform::RUBY spec.authors = ["Jesse Reiss", "Ryan Gerard", "Andrew Kiellor"] spec.email = [nil, "ko...
class AddNoticeToShippingMethods < ActiveRecord::Migration def change add_column :shipping_methods, :notice, :text end end
module ArchivesSpace class EnumMerge attr_reader :client, :enum, :old_value, :new_value def initialize(client, enum, old_value, new_value) @client = client @enum = enum @old_value = old_value @new_value = new_value end def merge result = client.get "config/enu...
class ChangeFormatDateRegistry < ActiveRecord::Migration def change change_column :registries, :last_registry, :datetime end end
class RemoveDefaultFromLocationOnPost < ActiveRecord::Migration def change change_column :posts, :location, :string end end
class List < ActiveRecord::Base default_scope { order(index: :asc) } end
class InstructionsController < ApplicationController def index @instructions = Instruction.all.inject({}) do |hash, instruction| hash[instruction.id] = { header: instruction.header, content: instruction.content, dog_name: instruction.dog.name } hash end end def s...
class Mobilfunkgeraet < ActiveRecord::Base attr_accessible :geraete_pin, :imei, :kommentar, :telefonnummer, :typ validates :imei, presence: true, uniqueness: true validates :geraete_pin, presence: true validates :telefonnummer, presence: true end
class Section::SettingWidget < Apotomo::Widget responds_to_event :submit def display(options = {}) @section = options[:section] render end def submit(evt) @section = Section.find evt[:id] if @section.update_attributes(evt[:section]) trigger :updateName, :section => @section end end e...
class RemoveTimeslot < ActiveRecord::Migration def change remove_column :appointments, :time_slot end end
class Comment < ActiveRecord::Base validates :content, presence: true validates :user_id, presence: true belongs_to :user belongs_to :parent, class_name: "Comment" has_many :replies, class_name: "Comment", foreign_key: :parent_id, dependent: :destroy has_many :likes private def self.comment_pa...
Rails.application.routes.draw do get 'orders/new' root 'static_pages#index' get '/signup', to: 'users#new' get '/addvehicle' ,to: 'vehicles#new' get '/login', to: 'sessions#new' post '/login', to: 'sessions#create' delete '/logout', to: 'sessions#destroy' get '/index', to: 'static...
class AddMobileToStaff < ActiveRecord::Migration def change add_column :staffs, :mobile, :string end end
require 'spec_helper' require 'will_paginate/finders/data_mapper' require File.dirname(__FILE__) + '/data_mapper_test_connector' require 'will_paginate' describe WillPaginate::Finders::DataMapper do it "should make #paginate available to DM resource classes" do Animal.should respond_to(:paginate) end ...
module Square # V1TransactionsApi class V1TransactionsApi < BaseApi # Provides summary information for a merchant's online store orders. # @param [String] location_id Required parameter: The ID of the location to # list online store orders for. # @param [SortOrder] order Optional parameter: The orde...
require 'spec_helper' describe "historicos/new" do before(:each) do assign(:historico, stub_model(Historico, :evento => "MyString", :observacao => "MyString", :data => "MyString", :remessa => nil ).as_new_record) end it "renders new historico form" do render # Run the ge...
module Octonaut desc "View your profile" command :me do |c| c.action do |global,options,args| user = @client.user print_user_table user end end desc "View profile for a user" arg_name 'login' command [:user, :whois] do |c| c.action do |global,options,args| login = args.shift ...
class ApplicationController < ActionController::Base protect_from_forgery helper_method :helper_method def helper_method raise "I will never ever be called!" end end
require 'rails_helper' RSpec.describe Step, type: :model do describe 'DB Columns' do it {should have_db_column(:sequential_number).of_type :integer} end describe 'validations' do it {should validate_presence_of :sequential_number} end describe 'belongs_to associations' do it {should belong_to :p...
module Refinery module Pages class TestimonialsSectionPresenter < Refinery::Pages::CollectionPresenter include ActiveSupport::Configurable # A presenter which knows how to render a single testimonial attr_accessor :output_buffer config_accessor :item_class, :item_tag, :quote_includes_cite...
class Product < ActiveRecord::Base belongs_to :company has_many :product_reviews validates :name, :price, :company_id, presence: true end
class AnimalInfo::Scraper def self.scrape_from_wikipedia(name) html = get_html(name) animal_name = html.search("h1#firstHeading").text properties = { name: animal_name } categories = ["Kingdom", "Phylum", "Class", "Order"] html.search("table.infobox.biota tr").each do |table_row| table_data...
class AddUploadAttemptOnSuccessfulUploadOnToAudits < ActiveRecord::Migration def change add_column :audits, :upload_attempt_on, :datetime add_column :audits, :successful_upload_on, :datetime end end
$: << File.dirname(__FILE__) + '/../lib/' require 'nabaztag/choreography' require 'test/unit' class ChoreographyTest < Test::Unit::TestCase class Choreography < Nabaztag::Choreography attr_reader :messages end def test_should_reproduce_api_example_2 ch = Choreography.new{ ear :left, 20, :forw...
require 'dotenv' Dotenv.load puts "Using proxy: #{ENV['INSTAGRAM_SCRAPING_PROXY_HOST']}" require "capybara" require 'selenium/webdriver' require 'capybara/dsl' require 'site_prism' $LOAD_PATH << File.expand_path("..", __FILE__) require 'settings' require 'page_objects/pages/instagram_page' require 'page_objects/pa...
require 'yt/collections/base' require 'yt/models/snippet' module Yt module Collections # @private class Snippets < Base private def attributes_for_new_item(data) {data: data['snippet'], auth: @auth} end # @return [Hash] the parameters to submit to YouTube to get the # ...
require 'spec_helper' describe Opendata::ListHelper, type: :helper, dbscope: :example do describe ".render_page_list" do context "without block" do subject { helper.render_page_list } before do @cur_site = cms_site create(:opendata_node_search_dataset) @cur_part = create(:ope...
class CreateCustomers < ActiveRecord::Migration def change create_table :customers do |t| t.string :nombres t.string :ap_paterno t.string :ap_materno t.string :sexo t.string :tipo_doc t.string :nro_doc t.string :email t.string :password t.date :fch_...
# frozen_string_literal: true class Protocol < ApplicationRecord belongs_to :card belongs_to :expert enum type_of_inspection: { first_visit: 0, second_visit: 1 } validates :type_of_inspection, :diagnosis, presence: true end
require 'fileutils' require 'tempfile' module Vfs module Drivers class Local class Writer def initialize out; @out = out end def write data @out.write data end end DEFAULT_BUFFER = 1000 * 1024 def initialize options = {} options = options.clone...
class AddSentColumnToApproval < ActiveRecord::Migration[5.0] def change add_column :approvals, :sent, :boolean, default: false end end
require 'test_helper' class PedidolineasControllerTest < ActionController::TestCase setup do @pedidolinea = pedidolineas(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:pedidolineas) end test "should get new" do get :new assert_respon...
#!/usr/bin/env ruby # minitest_test2spec # 20180729 # 0.6.1 # Changes since 0.5: # 1. Not opening each file multiple times now. # 2. Change of name: /minitest_assertion2spec/minitest_test2spec/. # 0/1 # 3. - require 'fileutils', since need of it was gone as of 0.6.0. # 4. /test\/assert_style.rb/test\/test_style.rb/. ...
class CommentsController < ApplicationController before_action :authenticate_user! before_action :set_post before_action :set_comment, only: [:edit, :update, :destroy] # GET posts/1/comments/1/edit def edit authorize @comment end # POST posts/1/comments # POST posts/1/comments.json def create ...
module SitescanCommon class AttributeNumber < ActiveRecord::Base self.table_name = :attribute_numbers has_one :product_attribute, as: :value, class_name: SitescanCommon::ProductAttribute after_save :product_reindex protected def product_reindex product_attribute.product_reindex if pr...
# frozen_string_literal: true class DashboardController < ApplicationController before_action :authenticate_user! def index @posts = Post.where(postable_type: 'User').of_followed_users(current_user.following).order('created_at DESC').page params[:page] @post = current_user.posts.build end def search ...
class Movie < ActiveRecord::Base has_many :nominations has_many :nominees, through: :nominations end
require 'spec_helper' describe UsersController do let(:user) { users(:owner) } before do log_in user end describe "#index" do it_behaves_like "an action that requires authentication", :get, :index it "succeeds" do get :index response.code.should == "200" end it "shows list o...
describe JWK::ECKey do let(:private_jwk) do File.read('spec/support/ec_private.json') end let(:public_jwk) do File.read('spec/support/ec_public.json') end let(:private_pem) do File.read('spec/support/ec_private.pem') end describe '#initialize' do it 'raises with invalid parameters' do ...
require 'rails_helper' RSpec.describe Answer, type: :model do it_behaves_like 'linkable' it_behaves_like 'votable' it_behaves_like 'commentable' describe 'associations' do it { should belong_to(:question) } it { should belong_to(:user) } it 'have many attached files' do expect(Answer.new.fil...
class Relationship < ActiveRecord::Base <<<<<<< HEAD belongs_to :follower, class_name: "User" belongs_to :followed, class_name: "User" validates :follower_id, presence: true validates :followed_id, presence: true ======= belongs_to :follower, class_name: "User" belongs_to :followed, class_name: "User" validat...
class DnsRecord < ApplicationRecord has_many :dns_record_hostnames has_many :hostnames, through: :dns_record_hostnames accepts_nested_attributes_for :dns_record_hostnames def hostnames=(s) hostname_array = s.to_s.split(',').map(&:strip) hostname_array.each do |hostname| hostnames << Hostname.whe...
class MangasController < ApplicationController before_action :get_manga, only: [:show] def index @mangas = Manga.order_manga.paginate page: params[:page], per_page: Settings.mangas.page @categories = Category.order(:name) if params[:q].present? @q = Manga.search(params[:q]) @mangas = @q.res...
class CreateJournalEntries < ActiveRecord::Migration[5.0] def change create_table :journal_entries do |t| t.text :gratitude t.text :motivation t.text :affirmation t.text :success t.text :lesson t.references :user, foreign_key: true t.timestamps end end end
class AddSuppressionsAndDataFileToSegments < ActiveRecord::Migration def change add_column :segments, :suppressions, :string add_column :segments, :data_file, :string end end
class Theme attr_accessor :name, :author, :version, :url, :about attr_reader :path def initialize(theme = nil) if theme @path = File.join(Merb.dir_for(:themes), theme) manifest = YAML::load_file(File.join(path, 'manifest.yml')) manifest.each_pair do |k, v| instance_variable_se...
#!/usr/bin/env ruby require 'loggz' example = Loggz.new #configuration example.redis_ip = "localhost" example.redis_password = "" example.redis_port = 6379 #display verbose output example.verbose = true #path to where the file is located(ie /mnt/nfs/Edgecast) It MUST have a trailing slash example.file_path = "/path/t...
class SurveyAssignments < ActiveRecord::Base attr_accessible :assigned_to, :user_id belongs_to :survey belongs_to :user belongs_to :assignee, foreign_key: :assigned_to, class_name: 'User' end
class AddNewFieldsToMpoints < ActiveRecord::Migration[5.0] def change add_column :mpoints, :messtation, :string add_column :mpoints, :meconname, :string add_column :mpoints, :clsstation, :string add_column :mpoints, :clconname, :string add_column :mpoints, :voltcl, :string add_column :mpoints,...
class UserController < ApplicationController before_filter :is_member_of, :only => [:show, :list, :destroy, :remove_user_from_submission] skip_before_filter :check_submiss_status layout "submission" # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html) # verify :method => :post, :only =...
# Your Names # 1) George Wambold # 2) Regina Compton # We spent [1.5] hours on this challenge. # Bakery Serving Size portion calculator. def serving_size_calc(item_to_make, order_quantity) #method with two arguments library = {"cookie" => 1, "cake" => 5, "pie" => 7} #hash unless library.include?(item_to_make...
SeoApp.configure do |config| # Postgress config config.db_url = ENV['DATABASE_URL'] config.adapter = 'sequel' end
require_relative 'boot' # Typically, rails uses a `require 'rails/all' here, but in our case, # since we override ActiveRecord with Sequel as our ORM of choice, we # only require what is needed require "active_model/railtie" require "active_job/railtie" require "action_controller/railtie" require "action_mailer/railti...
class CreateStudents < ActiveRecord::Migration def self.up create_table :students do |t| t.string :global_file_number t.integer :person_id t.integer :occupation_id t.datetime :busy_starts_at t.datetime :busy_ends_at t.string :blood_group t.string :blood_factor t.string :emer...
class Drink < ApplicationRecord belongs_to :shop has_many :takes, foreign_key: 'drink_id', dependent: :destroy has_many :users, through: :takes, source: :user end
class AddWillUnregisterToAttendees < ActiveRecord::Migration def self.up add_column :attendees, :will_unregister, :boolean, :default => false end def self.down remove_column :attendees, :will_unregister end end
class CreateRsvpInvitesSongs < ActiveRecord::Migration def self.up # Create the association table create_table :rsvp_invites_songs, :id => false do |t| t.integer :rsvp_invite_id, :null => false t.integer :song_id, :null => false end # Add table index add_index :rsvp_...
class AddIndexestoEverything < ActiveRecord::Migration[5.1] def change add_index :speeds, [:store_id, :shipping_speed], unique: true add_index :orders, :bc_order_id, unique: true add_index :amazons, :store_id, unique: true end end
class Admin::Api::MetricsController < Admin::Api::MetricsBaseController wrap_parameters Metric, include: [ :name, :system_name, :friendly_name, :unit, :description ] representer Metric ##~ sapi = source2swagger.namespace("Account Management API") ##~ e = sapi.apis.add ##~ e.path = "/admin/api/services/{serv...
require "application_system_test_case" class TuitsTest < ApplicationSystemTestCase setup do @tuit = tuits(:one) end test "visiting the index" do visit tuits_url assert_selector "h1", text: "Tuits" end test "creating a Tuit" do visit tuits_url click_on "New Tuit" fill_in "Tuit", wit...
module Baison class PackageDetail < Base # @price 单价 # @payment 实付金额 attr_accessor :sku, :num, :price, :payment def attributes { :sku => nil, :num => nil, :price => nil, :payment => nil } end end end
# # Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requir...
class CreateArticles < ActiveRecord::Migration def change create_table :articles do |t| t.references :product, index: true t.string :system_name t.string :title t.boolean :visible, default: false t.text :meta_keywords t.text :meta_description t.text :content t.time...
class Pet < ActiveRecord::Base belongs_to :user has_many :posts, dependent: :destroy has_many :comments, dependent: :destroy has_many :user_pet_follow_ships has_many :followers, through: :user_pet_follow_ships, source: :user default_scope { order('created_at ASC') } validates :avatar, attachment_content_type...
# frozen_string_literal: true class TaskCard::Component < ViewComponent::Base include TaskHelper with_collection_parameter :task def initialize(task:) @task = task end def upcase_task_slug @task.slug.upcase end end
#!/usr/bin/env ruby # # Usage: hr group # # Summary: Print a table under a grouped heading # # Help: Given a flat table of information, group by the first "column" and print beneath it as a heading # require 'optparse' require 'ostruct' options = OpenStruct.new options.field_separator = /,|:|\t/ options.output_field...
class Post < ActiveRecord::Base has_many :post_categories has_many :categories, through: :post_categories has_many :comments has_many :users, through: :comments accepts_nested_attributes_for :categories def categories_attributes=(category_info) category_info.values.each do |category_name| if cate...
require 'test_helper' class StructureTypesControllerTest < ActionDispatch::IntegrationTest setup do @structure_type = structure_types(:one) end test "should get index" do get structure_types_url assert_response :success end test "should get new" do get new_structure_type_url assert_resp...
class Dragon def initialize name @name = name @asleep = false @stuff_in_belly = 10 #he's full @stuff_in_intestine = 0 #no poo needed puts "#{@name} is born." end def feed puts "You feed #{@name}." @stuff_in_belly = 10 passage_of_time end def walk #take him for a dump...
shared_examples "validated_types" do context "nil" do before { instance.string1 = nil } it "is invalid" do expect(subject).to eql false end end context "empty String" do before { instance.string1 = "" } it "is invalid" do expect(subject).to eql false end end context "sp...
require 'minitest/autorun' require 'grader-utils' class TestParseArray < MiniTest::Unit::TestCase def test_that_it_accepts_array_with_square_brackets assert_equal GraderUtils.parse_array("[1,2,3]"), ["1", "2", "3"] assert_equal GraderUtils.parse_array("['1',2,3]"), ["'1'", "2", "3"] end def test_that_it...
# ========================================================================== # Project: Lebowski Framework - The SproutCore Test Automation Framework # License: Licensed under MIT license (see License.txt) # ========================================================================== module Lebowski module RSpec ...
class Course < ActiveRecord::Base has_many :students after_initialize :set_max_participants def set_max_participants self.max_participants = 30 end end
# -*- mode: ruby -*- # vi: set ft=ruby : Vagrant.configure(2) do |config| config.vm.box = "ubuntu/trusty64" config.ssh.insert_key = false config.ssh.shell = "bash -c 'BASH_ENV=/etc/profile exec bash'" config.vm.hostname = "online-booking" config.vm.network :private_network, ip: "192.168.3.100" ...
# questo script serve a creare un file di salvataggio "temporaneo" nel caso # in cui il gioco si chiuda in modo errato ed il giocatore rischia di perdere # i progressi di gioco. Purtroppo ci sono alcune chiamate ad API che chiudono # il gioco mentre si scrive da tastiera e non posso controllarne il comportamento. # Que...
class HomeController < ApplicationController def index @chatrooms = Chatroom.all end end
class Event < ApplicationRecord has_many :registrations, dependent: :destroy validates :name, :location, presence: true validates :description, length: { minimum: 25 } validates :price, numericality: { greater_than_or_equal_to: 0 } validates :capacity, numericality: { only_integer: true, greater_than: 0 } ...
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :ecm_tournaments_series, :class => 'Ecm::Tournaments::Series' do sequence(:name) { |i| "Serie ##{i}" } end end
#! /usr/bin/env ruby =begin gtk2/base.rb Copyright (c) 2006 Ruby-GNOME2 Project Team This program is licenced under the same licence as Ruby-GNOME2. $Id: base.rb,v 1.4 2006/11/03 19:40:44 mutoh Exp $ =end require 'glib2' require 'atk' require 'pango' begin require 'cairo' rescue LoadError end require 'gtk...
class Configuration attr_reader :uaa_endpoint attr_reader :client_name attr_reader :client_secret attr_reader :use_ssl def initialize uaa_endpoint, client_user_name, client_secret, use_ssl @uaa_endpoint = uaa_endpoint @client_name = client_user_name @client_secret = client_secret @use_ssl = u...
class CreateTerritories < ActiveRecord::Migration[5.0] def change create_table :territories do |t| t.string :name t.string :dsm t.float :leads_per_hour t.integer :number_of_stores t.integer :number_of_hours_worked t.integer :number_of_active_isps t.timestamps end e...
# frozen_string_literal: true # Copyright (c) 2018 Robert Haines. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by a...
# frozen_string_literal: true class Schedule < ApplicationRecord class Entity < Base expose :day do |schedule| schedule.date.day end expose :free_seats, if: ->(_, opt) { !(opt[:user]&.admin? || opt[:user]&.operator?) } expose :date, :count, :free_seats, if: ->(_, opt) { opt[:user]&.admi...
class ReconfigureRepository < ActiveRecord::Migration def change rename_column :repositories, :full_name, :provider_id add_column :repositories, :provider_slug, :string add_index :repositories, :provider_slug, unique: true end end
Rails.application.routes.draw do mount EricWeixin::Engine => "/eric_weixin" end