text
stringlengths
10
2.61M
#!/usr/bin/env ruby # Hpricot is an HTML/Web page processing library require "hpricot" puts "hpricot was loaded successfully" if defined? Hpricot
class Comment < ActiveRecord::Base validates :author_id, :post_id, :body, presence: true default_scope { order(created_at: :asc) } belongs_to :author, primary_key: :id, foreign_key: :author_id, class_name: :User belongs_to :post, primary_key: :id, foreign_key: :post_id, class_name: :Po...
require File.dirname(__FILE__) + '/sample_migration' require File.dirname(__FILE__) + '/../lib/spec/example/migration_example_group' describe :create_people_table, :type => :migration do before do run_migration end it 'should create a people table' do repository(:default).should have_table(:people) e...
class Question < ApplicationRecord belongs_to :subject, inverse_of: :questions has_many :answers accepts_nested_attributes_for :answers, reject_if: :all_blank, allow_destroy: true end
# модуль позволяет автоматом прописать # транслитерированный путь при создании экземпляра модели module SluggableModel extend ActiveSupport::Concern included do before_create :generate_slug def generate_slug self.slug = name.parameterize end def path self.class.name.underscore.plural...
class Admin::UsersController < Admin::ApplicationController def index @users = User.all end def send_activation_email #TODO setup backend job system UserMailer.activation_email(user,params[:content]).deliver_later head :ok end def login login_as(user) redirect_to "/courses" end...
# Запись в блоге class Post < ActiveRecord::Base include SortedByName include MultilingualModel include AutotitleableModel include SluggableModel translates :announce, :title, :heading, :keywords, :description, :content default_scope { order(:weight) } has_many :post_comments has_many :post_block...
require 'rails_helper' require 'csv' RSpec.describe VanService do before(:each) do @service = VanService.new end it 'can connect with VAN upon initialization' do expect(@service).to be_truthy end it 'can find the id of a person' do survey_results_1_person = {:firstName=>"Vogelsang", :...
require "spec_helper" describe Lita::Handlers::Standups, lita_handler: true, additional_lita_handlers: Lita::Handlers::Wizard do include Lita::Standups::Fixtures before do Lita::User.create(2, name: "User2") Lita::User.create(3, name: "User3") create_standups(3) create_standup_schedules(3) cre...
class UsersController < ApplicationController before_action :check_for_admin, :only => [:index] def index @users = User.all end def new @user = User.new end def create @user = User.new user_params if params["user"]["image"] cloudinary = Cloudinary::Uploader.upload( params[ "user" ]...
FactoryBot.define do factory :user do trait :invalid_name do name { nil } end trait :invalid_email do email { nil } end trait :invalid_password do password { nil } end trait :invalid_admin do admin { nil } end name { 'Valid name' } email { 'valid@mail.co...
class CreateSettlementTables < ActiveRecord::Migration[5.2] def change create_table :settlement_tables do |t| t.integer :order_id t.string :namsettlement_state t.string :payment_method t.timestamps end end end
class Dog attr_accessor :name,:age, :breed @@all = [] def self.all @@all end def initialize(name = nil, breed = nil, age = nil) @name = name @breed = breed @age = age @@all << self end end
require 'rails_helper' RSpec.describe "Following relations", type: :feature do before(:each) do @user = create(:user) login_as @user, :scope => :user end it "follow user" do user2 = create(:user) expect { visit root_path click_link "btn-user-#{user2.id.to_s}" }.to change(Relation...
class AddTotalsinvoice < ActiveRecord::Migration[5.2] def change add_column :quotations, :total_gross, :float end end
require 'test_helper' class Resources::ReviewsControllerTest < ActionController::TestCase def setup @controller.stub! :oauth_handshake, :return => true end # test "should get index" do # get :index # assert_response :success, @response.body # assert_not_nil assigns(:reviews) # end ...
# == Schema Information # # Table name: users # # id :integer not null, primary key # user_name :string(255) not null # password_digest :string(255) not null # created_at :datetime # updated_at :datetime # class User < ActiveRecord::Base validates :user_name, pres...
require 'spec_helper' describe EventInfo do before do @valid_attributes ={ app_session_id: 1, event_id: 2, track_id: 3, time: 10.0, properties: { "name" => "John Doe" } } EventInfo.any_instance.stub(:associate_track) {} end it "should create a new install...
class CreateSecretWordsTable < ActiveRecord::Migration[6.0] def change create_table :secret_words do |t| t.string :word t.string :hint t.integer :difficulty end end end
class FlowsController < ApplicationController # TODO: show, editにset_flowメソッドを追加 def index @flow = Tflow.all().eager_load(:task) end def show @flow = Tflow.find(params['id']) end def new end def edit @flow = Tflow.find(params['id']) end def create end def update respond_...
class Topic < ActiveRecord::Base has_many :posts, dependent: :destroy has_many :playlists, dependent: :destroy validates :name, length: { minimum: 5 }, presence: true validates :description, length: { minimum: 10 }, presence: true scope :visible_to, lambda { |user| user ? scoped : where(public: true) } end
class CreateJoinTableUserDoc < ActiveRecord::Migration[5.1] def change create_join_table :users, :docs do |t| t.index [:user_id, :doc_id] t.index [:doc_id, :user_id] end end end
class Specie < ApplicationRecord has_many :person_species, class_name: "PersonSpecie", dependent: :destroy has_many :people, through: :person_species, source: :person validates :name, uniqueness: true end
require 'wsdl_mapper/dom/type_base' require 'wsdl_mapper/dom/shallow_schema' module WsdlMapper module Dom class BuiltinType < TypeBase NAMESPACE = 'http://www.w3.org/2001/XMLSchema'.freeze extend ShallowSchema self.namespace = NAMESPACE def root self end end end end
require 'rrreader/channel_item' module Rrreader class Channel attr_accessor :description, :title, :link, :items def initialize @items = [] end end end
class ApplicationController < ActionController::Base around_action :_set_locale_from_param before_action :_redirect_to_root_domain # before_action :_sleep_some_time def _sleep_some_time sleep 2 end def _set_locale_from_param locale = params[:locale] if params[:locale].present? && I18n.available_lo...
# == Schema Information # # Table name: deployment_pipelines # # id :integer not null, primary key # created_at :datetime not null # updated_at :datetime not null # name :string indexed # env_id :integer # position :integer # template :boolean ...
require 'spec_helper' describe GroupDocs::Api::Helpers::MIME do subject do GroupDocs::Signature.new end describe '#mime_type' do it 'returns first MIME type of file' do types = ['application/ruby'] ::MIME::Types.should_receive(:type_for).with(__FILE__).and_return(types) types.should_re...
require 'test_helper' class ShopInfosControllerTest < ActionController::TestCase setup do @shop_info = shop_infos(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:shop_infos) end test "should get new" do get :new assert_response :succe...
require 'rspec' require 'rack/test' describe 'CRUD Bookmark App' do include ::Rack::Test::Methods def app ::Sinatra::Application end describe 'POST /bookmarks' do it 'creates a new bookmark' do get '/bookmarks' expect(last_response).to be_ok bookmarks = ::JSON.parse(last_response.bo...
class CreateUsers < ActiveRecord::Migration def up create_table :users do |t| t.column "first_name", :string, :limit => 25 #cria coluna nomeada first_name, do tipo string, com tamanho de 25 caracteres t.string "last_name", :limit => 50 #coluna string limite 50 caracteres t.string "email", :defau...
class CommentsController < ApplicationController before_filter :require_user def create @post = Post.find_by_slug(params[:post_id]) @comment = post.comments.new(params[:comment]) @comment.user = current_user if @comment.save redirect_to post_path(post) else render 'posts/show' end end end
module Fog module Compute class Google class MachineTypes < Fog::Collection model Fog::Compute::Google::MachineType def all(zone: nil, filter: nil, max_results: nil, order_by: nil, page_token: nil) opts = { :filter => filter, :max_results => max_results, ...
class PostsController < ApplicationController before_action :authenticate_user! def create @post = Post.new(post_params) @post.user_id = current_user.id @post.save flash[:create_post] = 投稿が完了しました! redirect_to posts_path end def show @user = current_user @new_post = Post.new @post =...
require 'spec_helper' describe Ecm::Tournaments::Tournament do context 'associations' do it { should belong_to :ecm_tournaments_series } it { should belong_to :ecm_tournaments_type } it { should have_many :ecm_tournaments_matches } it { should have_many :ecm_tournaments_participants } it { should...
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 #-- # Using Session include SessionsHelper #-- # Using RBAC include RBACAuthentication # find me at 'lib/...
class RemoveApprove < ActiveRecord::Migration def change remove_column :transaction,:approve end end
class Student < ActiveRecord::Base has_many :attempts def self.find_by_formatted_organization_id(entered_id) self.find_by_organization_id(entered_id.upcase) end end
class CreateIndexesForUserIds < ActiveRecord::Migration def change remove_column :alexas, :user_id, :integer remove_column :stops, :user_id, :integer add_reference :alexas, :user, index: true, foreign_key: true add_reference :stops, :user, index: true, foreign_key: true end end
class Users::RegistrationsController < Devise::RegistrationsController def create @user = User.new sign_up_params if @user.save super else render json: {status: :error1, html: t(".error")} end end private def sign_up_params params.require(:user).permit :name, :email, :password...
class Seed < ApplicationRecord has_one :fruit before_create :init scope :un_consumed, -> {where(consumed: false).order("RANDOM()").limit(1)} scope :consumed, -> {where(consumed: true).order(created_at: :desc).limit(10)} def attributes { id: id, label: label, consumed: consumed, ...
require 'rails_helper' RSpec.describe "qualificacao_passagens/index", :type => :view do before(:each) do assign(:qualificacao_passagens, [ QualificacaoPassagem.create!( :concretizado => false, :justificativa => "Justificativa", :nivel => "Nivel", :comentario => "Comentario",...
class ApplicationRecord < ActiveRecord::Base self.abstract_class = true def when_deadline(month) if self.persisted? # 締切日から❍ヶ月後 self.deadline_on = months_later(month: month, time: deadline_on) # ここに余りがあれば足す処理追加 if self.respond_to?(:division_remainder) self.deadline_on = days_lat...
class CreateUsers < ActiveRecord::Migration def self.up create_table :users do |t| t.string :domain_name t.string :screen_name t.string :nickname t.text :profile_text t.integer :kitaguchi_profile_id t.boolean :random_url, :default => false t.string :random_key t.boo...
class MessageBroadcastJob < ApplicationJob queue_as :default def perform(user, id) ActionCable.server.broadcast('messages', message: render_message(user), id: id) end private def render_message(user) ApplicationController.render(partial: 'messages/new_messages', locals: { user: user }) end end
require 'simplecov' SimpleCov.start require_relative '../lib/authentication.rb' require_relative '../lib/principal.rb' RSpec.describe Authentication do it 'can logout' do a = Authentication.new a.login(Principal.new('Sergio', 'Ramos', 'Director', 'pw2')) a.logout expect(a.logged).to be false end ...
require 'rails_helper' describe Location do before do mock_geocoding! end # allow mass assignment of describe "allow mass assignment of" do it { should allow_mass_assignment_of(:name) } it { should allow_mass_assignment_of(:address) } it { should allow_mass_assignment_of(:lat) } it { shou...
Rails.application.routes.draw do get '*path', to: "static#index", constraints: ->(request) do !request.xhr? && request.format.html? && !request.path.match(/^\/(assets|api)/) end root to: "static#index" end
begin require 'wesabe' module Bankjob class OutputFormatter class WesabeFormatter attr_accessor :username, :password, :account_number def initialize(credentials) @username, @password, @account_number = credentials.to_s.split(/ /, 3) if @username.blank? || @password.bl...
class AddColumnToMake < ActiveRecord::Migration[5.0] def change add_column :makes, :image, :string end end
module APND class Settings # # Settings for APND::MongoDB if you want persistence # class MongoDB attr_accessor :host attr_accessor :port attr_accessor :database def initialize @host = 'localhost' @port = 27017 @database = nil end def conn...
require 'sinatra' class AllButPattern Match = Struct.new(:captures) def initialize(except) @except = except @captures = Match.new([]) end def match(str) @captures unless @except === str end end def all_but(pattern) AllButPattern.new(pattern) end get all_but('/index') do puts "GET all_but ...
class AddBillableFlagToEvent < ActiveRecord::Migration def up add_column :events, :billable, :boolean, :default => true, :null => false Event.where(blackout: true).each do |e| e.update_column(:billable, false) end end def down drop_column :events, :billable end end
require 'pry-byebug' require 'sinatra' require 'rest-client' require 'json' require 'sinatra/base' class ListMore::Server < Sinatra::Application set :bind, '0.0.0.0' before do @body = request.body.read @body = "{}" if @body.length == 0 @params = JSON.parse(@body) puts "Got params: #{@params}" ...
ENV["RAILS_ENV"] ||= 'test' require File.expand_path("../../config/environment", __FILE__) require 'rspec/rails' require 'shoulda/matchers' require 'capybara/rails' require 'capybara/rspec' require 'sidekiq/testing/inline' require 'webmock/rspec' require 'factory_girl' require 'pry' require 'mandrill_mailer/offline' R...
# == Schema Information # # Table name: wechat_sub_menus # # id :integer not null, primary key # wechat_menu_id :integer # menu_type :integer # name :string(255) # key :string(255) # url :string(255) # class WechatSubMenu < ActiveRecord::Base validates_...
class SpeakerArea < ActiveRecord::Base belongs_to :speaker belongs_to :area end
class TestAuthenticationController < ApplicationController before_action :authenticate_user! def index render json: { message: 'Message Success!' }, status: :ok end end
class AddNeighborhoodToDeliverCoordinators < ActiveRecord::Migration def change add_column :deliver_coordinators, :neighborhood, :string, null: false, default: '' end end
class GcmNotificationController < ApplicationController before_filter :authenticate_user! before_filter :set_app layout 'gcms_notification_menu' def notification @notification = Rapns::Gcm::Notification.new end def create @notification = Rapns::Gcm::Notification.new(notification...
# You will write a method only_unique_elements that takes in an Array # The method returns a new array where all duplicate elements are removed. # You must solve this using a hash. def only_unique_elements(arr) newHash = Hash.new(0) arr.each{|x|newHash[x]=1} newHash.to_a.flatten().select{|x|x.is_a?(...
require 'rails_helper' RSpec.describe Item, type: :model do it { should belong_to(:section) } it { should have_many(:favorites) } it { should have_many(:users).through(:favorites) } end
require "./test/test_helper" class TeamRepoTest < MiniTest::Test def setup @team_repo = TeamRepo.new('./data/team_info.csv') end def test_team_repo_exists assert_instance_of TeamRepo, @team_repo end def test_team_repo_has_teams assert_equal 33, @team_repo.repo.count end end
require 'minitest/autorun' require 'minitest/rg' # require_relative '../bus' require_relative '../person' require_relative '../bus_stop' class TestBusStop < MiniTest::Test def setup @bus_stop = BusStop.new('Lothian Road') @passenger = Person.new('Stuart', 41) end def test_name assert_equal('Lothian...
describe SyntaxHighlighting::Pattern do let(:contents) do { "begin" => "begin_value", "end" => "end_value", "beginCaptures" => { "0" => { "name" => "begin_captures_value" } }, "endCaptures" => { "0" => { "name" => "end_captures_value" } }, "contentName" => "content_name_value", ...
class Ship attr_reader :member_cells def initialize @sunk = false @member_cells = [] end def sunk? @sunk end def sink! @sunk = true end def cell_count member_cells.count end def accept_cells(cell) member_cells << cell end def are_all_my_cells_hit? sink! if member_cells.all? { |cell| cel...
require_relative "live/state_view" require_relative "live/game_policy" require_relative "live/game_engine" require_relative "live/states_history" require_relative "live/file_reader" class LiveController def initialize @view = Live::StateView.new @policy = Live::GamePolicy.new @game_engine = Live::GameEng...
# Teapot v2.2.0 configuration generated at 2017-10-07 23:42:48 +1300 required_version "2.0" # Project Metadata define_project "botan" do |project| project.title = "Botan" project.summary = 'A cryptography library providing TLS/DTLS, PKIX certificate handling, PKCS#11 and TPM hardware support, password hashing, and...
require 'rails_helper' RSpec.describe User, type: :model do context 'validation tests' do it 'ensures email is present' do user = User.new(admin: false).save expect(user).to eq(false) end end end
class Customer include Mongoid::Document field :application, type: String field :application_id, type: String field :email, type: String field :token, type: String field :bypass, type: Boolean embeds_many :bypasses def self.find_or_create application, application_id, email, token, ip custom...
require 'uri' class ShortUrlApi < Grape::API content_type :json, 'application/json' format :json desc '短链详情列表' params do # requires :password, type: String, module: Md5, desc: '采用密码' optional :page, type: Integer, default: 1 optional :per, type: Integer, default: 10 end get '/u' do params...
require 'spec_helper' describe Height::Units::Millimeters do describe 'converts to' do before do @millimeters = Height::Units::Millimeters.new(1910) end it 'millimeters' do @millimeters.to_millimeters.should === @millimeters end it 'centimeters' do @millimeters.to_centimeters...
#!/usr/bin/env ruby require "bundler/setup" require "emconvert/version" require "emconvert/converter" require 'optparse' require 'fileutils' options = {:verbose => false, :backup => true} parser = OptionParser.new do|opts| opts.banner = "Usage: emconvert --verbose --backup files" opts.on('-v', '--verbose', 'Show ...
define :outer do _foo = params[:foo] || raise("foo is nil") execute 'outer test' do command "[[ ! -s #{params[:foo]} ]]" # params is in scope, parasm[:foo] has a value end inner 'explicit' do foo _foo # _foo is in scope, so it has a value end inner 'implicit' do foo params[:foo] # params is f...
module ApplicationHelper def full_title title title.empty? ? t("app_title") : title + " | " + t("app_title") end end
# == Schema Information # # Table name: user_route_relationships # # id :integer not null, primary key # follower_id :integer # route_id :integer # created_at :datetime not null # updated_at :datetime not null # class UserRouteRelationship < ActiveRecord::Base attr_accessi...
require 'test_helper' class GroupsControllerTest < ActionController::TestCase test "can get trending groups" do get :index assert_response :ok end test "can get group page" do get :show, id: 'gumi-appreciation-group' assert_response :ok assert_preloaded 'groups' end test "can get group ...
require 'rails_helper' describe 'atronaut index' do it 'user can see all astronauts' do astronaut_1 = Astronaut.create(name: 'John Glenn', job: 'engineer', age: 50) astronaut_2 = Astronaut.create(name: 'Buzz Aldren', job: 'conspiract theorist', age: 90) visit '/astronauts' expect(page).to have_con...
class Profile < ActiveRecord::Base belongs_to :user has_many :taggings, :as => :taggable has_many :tags, :through => :taggings validates_presence_of :name, :surname end
# frozen_string_literal: true module ErrorsCatcher extend ActiveSupport::Concern included do rescue_from ApiAuthentication::Errors::Auth::InvalidCredentials, with: :unauthorized_request rescue_from ApiAuthentication::Errors::Token::Missing, with: :unauthorized_request rescue_from ApiAuthentication::Er...
class Country < ActiveRecord::Base has_many :states accepts_nested_attributes_for :states has_many :permitted_destinations has_many :products, through: :permitted_destinations has_many :default_permitted_destinations has_many :users, through: :default_permitted_destinations def country_name "#{...
require 'json' module Actions module GladiatorsActions def generate_actions(data, actions) data.each do |k, v| if v.is_a?(Hash) v.each do |k, v| if k == "name" define_method ("greeting") do p "Going to death #{v}, salute you!" end elsif k == "weapon" v.each do |v| ...
# frozen_string_literal: true require_relative 'test_helper' module Dynflow module SemaphoresTest describe ::Dynflow::Semaphores::Stateful do let(:semaphore_class) { ::Dynflow::Semaphores::Stateful } let(:tickets_count) { 5 } it 'can be used as counter' do expected_state = { :tickets ...
class ReviewsController < ApplicationController # make @book accessable before_action :find_book before_action :find_review, only: [:edit, :update, :destroy] before_action :authenticate_user!, only: [:new, :edit] def new @review = Review.new end def create @review = Review...
json.array!(@contact_messages) do |contact_message| json.extract! contact_message, :id, :name, :author, :message json.url contact_message_url(contact_message, format: :json) end
feature 'players can enter their names on the screen' do scenario 'inputted names are displayed' do sign_in_and_play expect(page).to have_content("Josue vs. Hannah") end end
# frozen_string_literal: true module Diplomat # Methods for interacting with the Consul ACL Role API endpoint class Role < Diplomat::RestClient @access_methods = %i[list read read_name create delete update] attr_reader :id, :type, :acl # Read ACL role with the given UUID # @param id [String] UUID ...
# == Schema Information # # Table name: tables # # id :uuid not null, primary key # name :string # location :string # splited :boolean default(FALSE) # order_id :uuid # parent_id :uuid # status :integer # created_at :datetime not null # updated_at :datetim...
class Article < ActiveRecord::Base validates :title, presence:true, length:{minimum:5} validates :content, presence:true, length:{minimum:10} validates :status, presence:true scope :status_active,->{where(status:'Dirilis')} has_many :comments, dependent: :destroy end
require 'rack' require 'active_support' require 'active_support/concern' require 'active_support/core_ext/kernel/reporting' require 'dionysus/string/version_match' module Circuit # Compatibility extensions for Rack 1.3 and Rails 3.1 module Compatibility # Make Rack 1.3 and ActiveSupport 3.1 compatible with cir...
# This railtie is for bootstrapping the pawnee gem only # It adds the config/pawnee directory to the loadpath if defined?(Rails) module Pawnee class Railtie < Rails::Railtie initializer "pawnee.configure_rails_initialization" do puts "INITIALIZE1" path = (Rails.root + 'config/pawnee')...
require 'spec_helper' require 'json' docs = JSON.parse(File.read('spec/fixtures/cjk_map_solr_fixtures.json')) stanford_docs = JSON.parse(File.read('spec/fixtures/cjk_stanford_fixtures.json')) describe 'CJK character equivalence' do include_context 'solr_helpers' def add_single_field_doc char solr.add({ id: 1...
$LOAD_PATH.unshift File.dirname(__FILE__) require 'smtpapi/version' require 'json' module Smtpapi # # SendGrid smtpapi header implementation # class Header attr_reader :to, :sub, :section, :category, :unique_args, :filters attr_reader :send_at, :send_each_at, :asm_group_id, :ip_pool def initialize...
class CreatePhotos < ActiveRecord::Migration def change create_table :photos do |t| t.string :user_id t.string :uid t.string :caption t.string :name t.string :url t.datetime :taken_at t.integer :likes t.timestamps ...
class Func module InitIvars def initialize(*args, &block) params = Params.new method(:initialize) if block && !params.block? raise ArgumentError, "#{self.class}#initialize does not accept a block" end kwargs = args.pop if params.keys? params.each_with_arg_index do |name, in...
# encoding: US-ASCII require 'stringio' require 'binary_struct' require 'miq_unicode' # //////////////////////////////////////////////////////////////////////////// # // Data definitions. # TODO: reserved1 is the infamous magic number. Somehow it works to preserve # case on Windows XP. Nobody seems to know how. Here...
module Yaks class Resource class Form class Field include Yaks::Mapper::Form::Field.attributes.add(error: nil) undef value def value if type.equal? :select selected = options.find(&:selected) selected.value if selected else @va...
class Project < ActiveRecord::Base attr_accessible :title has_many :memberships, { dependent: :destroy, inverse_of: :project } has_many :users, { through: :memberships } end
class AddEnglishColumnToGenre < ActiveRecord::Migration def change add_column :genres, :english, :boolean, default: true end end
require './app/simple/basic_calculator_engine' require 'test/unit' require 'test/unit/notify' class BasicCalculatorEngineTest < Test::Unit::TestCase def setup() @calc = BasicCalculatorEngine.new() end def test_accepts_new_number() # Intent revealing name # Arrange num = 25.35 # Ac...