text
stringlengths
10
2.61M
class AddProcessingToUsers < ActiveRecord::Migration def change add_column :uploads, :dwc_processing, :boolean end end
When /^I visit "([^"]+)"$/ do |page| visit(page) end Then /^I should be on "([^"]+)"$/ do |page| current_url.should == page end Then /^Firebug should be active$/ do evaluate_script('!!(window.console && (window.console.firebug || window.console.exception))').should be_true end
module Enocean module Esp3 class Rorg4BS < Radio def self.rorg_code 0xa5 end def self.create(data=[0,0,0,0], sender_id=[0xff,0xff,0xff,0xff], status = 0) base_data = [rorg_code] + data + sender_id + [status] return self.new(Enocean::Esp3::Radio.type_id, base_data) ...
class CartsController < ApplicationController def show @staches = @cart.staches end end
class CreateMemoryComments < ActiveRecord::Migration[5.2] def change create_table :memory_comments do |t| t.references :pet t.references :memory t.string :comment t.timestamps end end end
class AddUnmatchedToProjectMedias < ActiveRecord::Migration[6.1] def change add_column :project_medias, :unmatched, :integer, default: 0 add_index :project_medias, :unmatched # add mapping for unmatched index_alias = CheckElasticSearchModel.get_index_alias client = $repository.client options =...
require 'pry' class Day12 class Point3D attr_accessor :x, :y, :z def initialize(x = 0, y = 0, z = 0) @x = x @y = y @z = z end def g(c1, c2) case when c1 == c2 0 when c1 > c2 -1 when c1 < c2 1 end end def gravity(other) ...
require 'spec_helper' require 'referencia' describe Referencia do before :each do # Defino los valores que tomarán los atributos primero y luego le paso las variables al constructor del objeto Referencia # Por conveniencia, el valor V es igual a Vacio, es decir: si un atributo tiene el valor V es como si no ...
class User < ActiveRecord::Base class NotLoggedIn < StandardError;end class PermissionDenied < StandardError;end acts_as_authentic attr_protected :points,:admin attr_readonly :username named_scope :better_than, lambda { |points| {:conditions =>["points > :p",{:p=>points}]}} named_scope :worse_than, lambda...
Before("@user_agent") do |scenario| @user_agent = true @scenario = scenario end
require 'attr_extras' require 'json' require 'uri' require 'oauth2' class CardSide pattr_initialize :side_num, :side_type def to_json(_) {'sideNum' => side_num, 'sideType' => side_type}.to_json end end class Card pattr_initialize :card_number, :card_sides def to_json(_) {'car...
# Account Plans # Given /^(provider "[^"]*") allows to change account plan (directly|only with credit card|by request)?$/ do |provider,mode_string| mode = change_plan_permission_to_sym(mode_string) provider.set_change_account_plan_permission!(mode) end Given /^(provider "[^"]*") does not allow to change account pl...
class TimeSlot < ActiveRecord::Base has_many :meetings has_many :schedules, through: :meetings def self.create_time_slots(schedule, options = {period: 60, start_time: 0, end_time: 1440, start_day: 0, end_day: 7}) end_time = options[:end_time].to_i start_time = options[:start_time].to_i p...
class CreateEcmTournamentsSets < ActiveRecord::Migration def change create_table :ecm_tournaments_sets do |t| t.integer :first_team_score t.integer :second_team_score # associations t.references :ecm_tournaments_match t.timestamps end add_index :ecm_tournaments_sets, :ecm_t...
class PostSerializer < ActiveModel::Serializer attributes :id, :content, :user_id, :location_id, :location, :user, :date, :is_image, :post_comments, :day, :day_id def date return object.created_at.strftime("%I:%M %p ~ %m.%d.%Y") end def user ActiveModel::SerializableResource.new(object.user, each_ser...
class CustomersController < ApplicationController # GET /customers # GET /customers.json def index @customers = Customer.includes([:invoices, :payments]).order(:name).all render json: @customers end # GET /customers/1 # GET /customers/1.json def show @customer = Customer.includes(:invoices)....
# this class models RAAC behaviour without trust (i.e. risk budgets and static intervals) class Raac def initialize # superclasses can override this value, setting to 0 to disable risk budgeting @budget_decrement = Parameters::BUDGET_DECREMENT # track obligations @active_obligations = Hash.new { |h...
require 'slop' require 'traject' require 'traject/indexer' module Traject # The class that executes for the Traject command line utility. # # Warning, does do things like exit entire program on error at present. # You probably don't want to use this class for anything but an actual # shell command line, if y...
require 'rails_helper' RSpec.describe TradingStrategyService do let(:user) { User.create!( email: 'foo@bar.com', password: 'abcdabcd', huobi_access_key: 'oo', huobi_secret_key: 'ooo', trader_id: trader.id ) } let(:trader) { Trader.create!(webhook_token: 'oo', email: 'a@...
class ApplicationController < ActionController::Base include MicropostsHelper before_action :configure_permitted_parameters, if: :devise_controller? before_action :set_search_valiables # # 記事検索、ユーザー検索の初期設定 # @param [Array] post_search_result_count 記事検索結果件数を求める際に対象とする配列 # @param [Array] post_search_result...
class ImagesController < UIViewController include BW::KVO # 画像のURL(NSURL)の入った配列 attr_accessor :image_urls, :current_page, :current_thumbnail_page, :parent LOADING_IMAGE = UIImage.imageNamed('loading.png') ERROR_IMAGE = UIImage.imageNamed('error.png') RETRY_COUNT = 2 RECYCLE_BUFFER = 2 def init i...
class Participation < ApplicationRecord require 'stripe' belongs_to :participant belongs_to :study belongs_to :timeslot has_many :participation_requirements before_create :ensure_unique # Filterrific config filterrific( default_filter_params: { sorted_by: 'created_at_asc' }, available_filters...
# t.integer "server_id", null: false # t.string "nickname", null: false # t.string "hostname", default: "ricer.gizmore.org", null: false # t.string "username", default: "Ricer", null: false # t.string "realname", default: "Ricer I...
class UrlSanatizator < Callable PROTOCOL_REGEXP = /(https?:\/\/)|(www\.)/ def initialize(url:) @dirty_url = url end def call return nil if @dirty_url.nil? sanitanize() end private def sanitanize local_url = @dirty_url.strip local_url = @dirty_url.downcase.gsub(PROTOCOL_REGEXP, '')...
# fast version def simplify_fraction(numerator, denominator, result) greatest_common_divsor = gcd(numerator, denominator) result[0] = numerator / greatest_common_divsor result[1] = denominator / greatest_common_divsor end def gcd(a, b) while b > 0 temp = b b = a % b a = temp end a end # sl...
require_relative '../../spec_helper' describe 'resurrector', type: :integration, hm: true do with_reset_sandbox_before_each before do create_and_upload_test_release upload_stemcell end let(:cloud_config_hash) do cloud_config_hash = Bosh::Spec::NewDeployments.simple_cloud_config cloud_config_...
module Platforms module Yammer module Api # Networks on Yammer # @author Benjamin Elias # @since 0.1.0 class Networks < Base # Get the user's current Network # @param options [Hash] Options for the request # @param headers [Hash] Additional headers to send with the...
class Api::V1::SmDirectoryController < Api::ApiController require 'json' respond_to :json # == POST SOCIAL MEDIA DIRECTORY for a new movie by TMDB_ID # === POST /api/v1/sm_directory/ # movietech.herokuapp.com/api/v1/sm_directory/<tmdb_id> # adds social media directory for movie referenced by tmdb id w...
require 'rails_helper' RSpec.feature "Resources", type: :feature do let(:user) { create(:user_with_path) } let(:subject) { create(:subject) } scenario "shows a resource with Markdown content" do resource = create(:markdown, :published, subject: subject, content: "Hello World") login(user) visit sub...
class ExportsController < ApplicationController authorize_resource class: false def index end def resx if params[:culture] language = Language.find_by_culture_string(params[:culture]) send_data render_resx(language), filename: resx_file_name(language, false) else files = Hash[Languag...
class AddPostToPostComments < ActiveRecord::Migration def change add_reference :post_comments, :post, index: true end end
class Season < ActiveRecord::Base attr_accessible :name, :year has_many :products def name_year "#{name} #{year.year}" end end
require 'spec_helper' describe Bugsnag::Delivery::Fluent do it 'has a version number' do expect(Bugsnag::Delivery::Fluent::VERSION).not_to be nil end it 'registered to Bugsnag::Delivery' do expect(Bugsnag::Delivery[:fluent]).to eq(described_class) end describe '.deliver' do let(:fluent_logger) ...
class Message < ApplicationRecord belongs_to :photos, optional: true with_options presence: true do validates :name validates :text end end
module Moonrope class InstallGenerator < Rails::Generators::Base desc "This generator creates your a Moonrope directory structure" def generate_directories empty_directory 'api/controllers' empty_directory 'api/helpers' empty_directory 'api/structures' end end end
require File.expand_path(File.dirname(__FILE__) + '/spec_helper') describe RapperLite do Dir["spec/fixtures/testcases/*/"].each do |folder| name = File.basename( folder ) paths = [ { :results => "tmp/*.js", :expecteds => "#{folder}expected/*.js", }, { :results =...
class ProjectMediaProject < ActiveRecord::Base attr_accessor :previous_project_id, :set_tasks_responses include CheckElasticSearch include CheckPusher include ValidationsHelper has_paper_trail on: [:create, :update], if: proc { |_x| User.current.present? }, class_name: 'Version' belongs_to :project bel...
# encoding: utf-8 module Faceter module Functions # Break the array to array of consecutive items that matches each other # by given function # # @param [Array] list # @param [#call] fn # # @return [Array] # def self.claster(list, fn) list.each_with_object([[]]) do |e, a| ...
require 'rails_helper' describe "user visits destinations edit page" do context "as an admin" do it "allows admin to edit destinations" do admin = create(:user, role: 1) destination = create(:destination) allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(admin) ...
require 'rubygems' require 'spec' require 'backseat' include Backseat::Helpers describe 'a simple test' do before(:all) do Backseat.load! @driver = Backseat::Driver.new(:firefox) end it "should do some basic navigation" do @driver.get('http://localhost:3000/products') @driver.should have_at_l...
require 'rails_helper' describe PeerEval, type: :model do describe 'associations' do it { should belong_to(:user) } it { should belong_to(:creator).class_name("User") } it { should belong_to(:milestone) } end describe 'validations' do it { should validate_presence_of(:milestone) } it { shou...
class AddOriginalAmountToBlockchainTransactions < ActiveRecord::Migration def down remove_column :spree_blockchain_transactions, :order_total end def up add_column :spree_blockchain_transactions, :order_total, :decimal end end
class TradeGood < ActiveRecord::Base # serialize :available # serialize :purchase_dm # serialize :sale_dm has_many :broker_trade_goods has_many :trade_code_goods has_many :available_trade_code_goods, -> {where(kind: 'available')}, class_name: "TradeCodeGood" has_many :available_trade_codes, through: :av...
class Ships attr_reader :validated_coordinates, :game_board def initialize(validated_coordinates, game_board = GameBoard.new) @validated_coordinates = validated_coordinates @game_board = game_board end def mark_ships @validated_coordinates.each do |coordinate| ship_placement = @game_board....
class RemoveFriend < ActiveRecord::Migration def up drop_table :friends end def down create_table :friends do |t| t.integer :user_id t.string :name t.boolean :declared t.date :last_accompanied t.integer :accompaniment_frequency t.timestamps end end end
require 'test_helper' class TitlematchesControllerTest < ActionController::TestCase setup do @titlematch = titlematches(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:titlematches) end test "should get new" do get :new assert_respons...
module ApplicationHelper def nav_categories (cat) cat.map do |c| if c.articles.count > 0 content_tag :li do link_to c.name, category_path(c.permalink) end end end.reject{ |e| e.nil? }.reduce(&:+) end def page_title site_name, title if action_name == 'home' ...
module EasyPatch module DateHelperPatch def self.included(base) base.send(:include, InstanceMethods) base.class_eval do def time_ago_in_words_ex(from_time, label_not_expired = "", label_expired = "", include_seconds = false) result = time_ago_in_words(from_time + 1.day, include_se...
def get_name puts "I'm great at conversions. What's your name?" gets.chomp end def get_feet welcome_name puts "Welcome #{welcome_name}!!! How many feet tall are you?" height_feet = gets.chomp.to_i if height_feet.zero? puts "Zero feet tall? Try again:" height_feet = get_feet welcome_name ...
require 'optparse' require "#{File.dirname(__FILE__)}/auth.rb" require File.expand_path(File.dirname(__FILE__) + '/../googlepub') module Googlepub class Options BANNER = <<-EOS Googlepub it gem for Google Android Publisheing API. Abilities: 1) Store Listing 2) APK - All tracks 3) In-App Purchases (Managed an...
# frozen_string_literal: true require 'spec_helper' RSpec.describe StringLengthLastWord do let(:error_message) { 'String cannot be less than 1 or greater than 104 characters' } let(:challenge) { described_class.new(str).call } describe '.call' do context "when phrase ' fly me to the moon '" do ...
class AnswersController < ApplicationController before_action :signed_in_user, only: :show def show @answers = Answer.where("question_id = #{params[:id]}") @correct = @answers.where("correct_answer = true").shuffle.first @incorrect = @answers.where("correct_answer = false").shuffle.take(3) @final = @correct ...
class UpdateGame @queue = :update_game def self.perform(game_id) Game.find(game_id).refresh_status! end end
json.array!(@dinnings) do |dinning| json.extract! dinning, :id, :quantity, :price, :rate, :user_id json.url dinning_url(dinning, format: :json) end
class CreateMedicines < ActiveRecord::Migration def change create_table :medicines do |t| t.string :nombre t.string :cantidad t.text :indicaciones t.string :laboratorio t.string :composicion t.text :posologia t.text :detalle t.string :efectos_colaterales t.str...
class RenameColumnLeadInMovies < ActiveRecord::Migration def change rename_column :movies, :lead_actor_or_actress, :lead end end
class Country < ApplicationRecord mount_uploader :country_image, CountryUploader has_many :states has_many :cities has_many :companies has_many :places has_many :nodes validates :country_name, presence: true, length: { minimum: 3 } validates :country_name, uniqueness: true e...
module Input def get_name print "What is your name? " name = gets.chomp.downcase.split(" ").each {|word| word.capitalize!}.join(" ") print %x{clear} name end def get_guess guess = gets.chomp.downcase if guess == "save" else if guess.length > 1 puts "A valid guess must only be one letter" g...
class StaticPagesController < ApplicationController # Displays Contact us def contactus @static_page = StaticPage.find_by_name("contactus") render "contactus" end # Displays About us def aboutus @static_page = StaticPage.find_by_name("aboutus") render "aboutus" end # Displays faq def...
require 'minitest/spec' require 'minitest/autorun' require File.expand_path(File.join('..', 'lib/parser.rb'), File.dirname(__FILE__)) require File.expand_path(File.join('..', 'lib/pbxproj_validator.rb'), File.dirname(__FILE__)) describe Pbxproj::PbxProject do describe "printing" do before do content = <<'...
# frozen_string_literal: true require_relative '../../lib/utils/normalize_content' # @param [Discordrb::Events::MessageEventHandler] event def roll(event) content = normalize_content event.content puts content event.channel.send_embed('') do |embed| embed.title = 'You made a roll!!' embed.description = ...
require_relative '../rails_helper' describe FrontendHomepageController do describe "GET #show" do it "assigns the correct homepage to @homepage" do homepage = create(:homepage_published) get :show expect(assigns(:homepage)).to eq(homepage) end it "displays the homepage" do homepa...
class AddIconToCategory < ActiveRecord::Migration def change add_column :categories, :icon, :string, default: nil end end
class Tag < ActiveRecord::Base has_many :posts, :through => :post_tags has_many :post_tags has_many :services, :through => :service_tags has_many :service_tags validates :name, presence: true end
attributes *ComboItem.column_names - ['created_at', 'updated_at', 'name', 'menu_id'] if locals[:item].gmi?(locals[:menu_id]) #List of items in GMI child :combo_item_categories => "GMI_items" do attributes :sequence, :quantity node(:categories) do |c| partial('category/items', :object => c.cate...
class TopicsController < ApplicationController before_action :set_topic_id, only: [:show_topic, :edit, :destroy] before_action :set_post_id, only: [:edit_post] def index @project = Project.find(params[:id]) @topics = @project.topics.order(important: :desc) end def make_important topic = Topic.find(params...
require 'spec_helper' RSpec.describe Facing do let (:valid_facing) { Facing.new(:south) } let (:invalid_facing) { Facing.new(:invalid) } describe 'valid?' do context 'a valid context' do it { expect(valid_facing.valid?).to be_truthy } end context 'an invalid context' do ...
# module API module Railsapp module V1 class Videoapi < Grape::API include Railsapp::V1::Defaults format :json resource :videoapi do desc "Return all videos" get "", root: :videos do error!({:error_message => "Please provide a video id."}, 422) end des...
module StoryboardElements def self.table_name_prefix 'storyboard_elements_' end end
class ReviewContentsController < ApplicationController # GET /review_contents # GET /review_contents.json def index @review_contents = ReviewContent.all respond_to do |format| format.html # index.html.erb format.json { render json: @review_contents } end end # GET /review_contents/1 ...
require 'rails_helper' describe 'frontend routes', type: :routing do describe 'root_path' do it 'routes to static_pages#home' do expect(get: '/').to route_to( controller: 'static_pages', action: 'home', locale: 'en' ) end end describe 'courses_path' do it 'routes ...
require 'wsdl_mapper/svc_desc/envelope' require 'wsdl_mapper/svc_desc/fault' require 'wsdl_mapper/deserializers/type_directory' module WsdlMapper module SvcDesc SoapTypeDirectory = WsdlMapper::Deserializers::TypeDirectory.new FaultDeserializer = SoapTypeDirectory.register_type(['http://schemas.xmlsoap.org/s...
require 'yaml' module PicMov class Settings SOURCE_FOLDER = "source_folder" TARGET_FOLDER = "target_folder" SETTINGS_FILE = "settings.yml" def self.source_folder settings[Settings::SOURCE_FOLDER] end def self.target_folder settings[Settings::TARGET_FOLDER] end def self...
# frozen_string_literal: true require 'rgeo/geo_json' module GeoJSON class Decoder class MissingGeometry < StandardError; end def call(json) RGeo::GeoJSON.decode(json).tap do |maybe_geo| raise MissingGeometry, 'failed to decode into known geometry' if maybe_geo.nil? end end end end...
# frozen_string_literal: true class UserMailer < ActionMailer::Base include LogWrapper LOG_TAG = "UserMailer" default :from => '"MyLibraryNYC Admin" <no-reply@mylibrarynyc.org>' ## # Let the user know they've successfully unsubscribed from regular notification emails. # NOTE: Does not get used at this ti...
class PersonalOrdersController < ApplicationController def index redirect_to order_path(params[:order_id]) end def new @personal_order = PersonalOrder.new @parent_order = get_parent_order end def create @parent_order = get_parent_order @personal_order = PersonalOrder.new(personal_order_...
require 'rails_helper' RSpec.describe User, type: :model do context 'validation tests' do let(:user) { build(:user) } it 'ensures email is present' do user.email = nil expect(user.save).to eq(false) end it 'ensures password is present' do user.password = nil expect(user.save...
class ShortResponse < ApplicationRecord belongs_to :short_question belongs_to :organization validates :response, :presence => true end
ActionView::Helpers::FormBuilder.class_eval do # YAML TAGS # generates form tags that work with the YAML CSS-Framework def yaml_text_field(attr, label = nil) yaml_tag self.text_field(attr), self.label(attr, label), has_errors(attr) end def yaml_email_field(attr, label = nil) yaml_tag self.email_field...
require 'active_model' module Baison class Base include ActiveModel::Model include ActiveModel::Serializers::JSON class_attribute :resource class_attribute :params attr_accessor :logger def initialize(args) @logger = Logger.new(STDOUT) super args end def save js...
class AddImageNameToPaintings < ActiveRecord::Migration def change add_column :paintings, :image_name, :string end end
class CollisionDetector attr_reader :moving_element, :static_elements def initialize(moving_element:, static_elements:) @moving_element = moving_element @static_elements = static_elements end def detect! close_elements = static_elements.reject! do |element| G::distance( moving_eleme...
#!/usr/bin/env ruby gem = Gem::Specification::load("rumrunner.gemspec") pkg = "pkg/#{gem.full_name}.gem" rum gem.name do tag gem.version.to_s env :RUBY_VERSION => ENV["RUBY_VERSION"] || "latest" stage :install stage :test => :install stage :build => :test artifact pkg => :build desc "Push `#{pkg}` t...
class ApplicationController < ActionController::Base protect_from_forgery with: :exception before_action :set_locale def set_locale I18n.locale = params[:lang] || I18n.default_locale end def default_url_options(options = {}) { lang: I18n.locale == I18n.default_locale ? nil : I18n.locale } end ...
# Create execution history table class CreateExecutionHistories < ActiveRecord::Migration[4.2] def change create_table :execution_histories do |t| t.references :user, null: false t.foreign_key :users, on_delete: :cascade, on_update: :cascade t.references :notebook, null: false t.foreign_ke...
# Customer User Type # # has_many tickets class Customer < User has_many :tickets default_scope -> {includes(:user_type).where(user_types: {name: 'customer'})} end
#!/usr/bin/ruby -rubygems # encoding: utf-8 require_relative 'lib/build_fojas' puts 'Iniciando Comanda: fojas con salsa de FOXML, término medio.' begin if ARGV.length != 1 raise ArgumentError.new "Se esperaba solo un argumento (la ruta al archivo INI de configuración para el proceso)." exit else ini_...
require 'spec_helper' describe ProductsController do let(:authenticated_user) { double("authenticated user", { :id => 42, }) } describe 'POST #create', wip: true do before do subject.stub(current_user: authenticated_user) end let(:valid_attributes) { { name: "Foo Pr...
class Comment < ApplicationRecord belongs_to :commentable, polymorphic: true belongs_to :owner, class_name: "User", optional: true belongs_to :report, optional: true before_create :set_commentable_type validates :body, presence: true validates :report, presence: {unless: -> { commentable_type == "Activity...
################################### # # EVM Automate Method: InspectMe # # Notes: Dump the objects in storage to the automation.log # ################################### begin @method = 'InspectMe' $evm.log("info", "#{@method} - EVM Automate Method Started") # Turn of verbose logging @debug = true ########...
# copied from: http://lucatironi.net/tutorial/2015/08/23/rails_api_authentication_warden/?utm_source=rubyweekly&utm_medium=email require 'rails_helper' RSpec.shared_examples 'api_controller' do describe 'rescues from ActiveRecord::RecordNotFound' do context 'on GET #show' do before { get :show, { id: 'no...
class AddSubcategoryToCategory < ActiveRecord::Migration[6.1] def change add_reference :categories, :subcategory, null: false, foreign_key: {to_table: :categories}, index: true end end
class ClassMaterial < ApplicationRecord belongs_to :lecture has_one_attached :upload end
module Carnivore def diet puts 'meat' end def teeth puts 'sharp' end end module Herbivore def diet puts 'plant' end def teeth puts 'flat' end end module Nocturnal def sleep_time puts 'day' end def awake_time puts 'night' end end module D...
# Instance variables begin with @ # Class variables begin with @@ class Monster @@num_of_monsters = 0 # Use "end" to conclude method, similar to {} def initialize(id, name, place) @monster_id = id @monster_name = name @monster_place = place end # Use # to concatenate variables with strings ...
class Song < ApplicationRecord validates :artist, presence: true validates :name, presence: true end
class Backer def initialize(name) @name = name end attr_accessor :name def back_project(project) ProjectBacker.new(project,self) end def backed_projects pair_list = ProjectBacker.all.select {|projback| projback.backer == self } pair_list.map {|pair| pair.pro...
# Redmine - project management software # Copyright (C) 2006-2011 Jean-Philippe Lang # # 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, or (at your option) any...
class OpenJtalk VERSION = "0.8.0" HTS_VERSION = "1.09" OPEN_JTALK_VERSION = "1.08" end
# frozen_string_literal: true require 'rails_helper' RSpec.describe Adapter::Adapters::Cast do describe '.new' do subject(:subject_class) { described_class.new(value) } context 'when params is valid' do let(:value) { { query: 'query' } } it 'response with valid array keys' do expect(subje...