text
stringlengths
10
2.61M
class CreateWorkflowComments < ActiveRecord::Migration def change create_table :workflow_comments do |t| t.string :title t.text :body t.integer :score t.references :author, index: true t.references :comment_parent, index: true t.references :workflow_information, index: true ...
class Contentr::FilesController < Contentr::ApplicationController # The default action to render a view def show() file = Contentr::File.where(slug: params[:slug]).first if file send_file file.actual_file, disposition: 'inline' else render text: 'Not Found', status: '404' end end end...
FactoryGirl.define do factory :item do body "Item Body" created_at Time.now lifespan 10 factory :private_item do public false end end end
class Pokemon include Mongoid::Document include Mongoid::Timestamps field :pokemon_id, type: Integer field :name_ja, type: String field :name_en, type: String field :rare, type: Integer has_many :poke_locs, primary_key: "pokemon_id" has_many :watched_pokemons, primary_key: "pokemon_id" validates_numer...
require File.dirname(__FILE__) + '/../test_helper' class NoteTest < ActiveSupport::TestCase should_have_db_columns :body, :created_by, :partner_id def setup @account = Factory(:account) @user = Factory(:user, :account => @account) @partner = Factory(:partner, :creator => @user, :account => @account)...
require "rails_helper" feature "edits account", %Q{ As an authenticated user I want to update my information So that I can keep my profile up to date } do # ACCEPTANCE CRITERIA # * User can edit first_name # * User can edit last_name # * User can edit email # * If all information is comple...
# email_parser.rb # Build a class EmailParser that accepts string of unformatted emails class EmailParser attr_accessor :email, :email_parser def initialize(email_file) @email_parser = email_file end # #parse on the class should separate unformatted emails into unique email addresses # Delimiters to support...
class LikesController < ApplicationController before_action :set_variables def like like = current_user.likes.new(error_id: @error.id) like.save end def unlike like = current_user.likes.find_by(error_id: @error.id) like.destroy end def set_variables @error = Error.find(params[:error_i...
class ProjectsController < ApplicationController before_action :load_projects_kind, except: :index before_action :check_machines, except: :index def index unless current_user.has_machines? flash.now[:alert] = 'Remember! You must have a machine for management projects.' end @projects = current_...
require 'rails_helper' describe "Category" do it "is valid with a name" do category = Category.new(name: "phamkhanh") expect(category).to be_valid end it "is invalid without a name" do category = Category.new(name: nil) category.valid? expect(category.errors[:name]).to include("can't be blan...
# This migration comes from platforms_core (originally 20200308091104) class CreatePlatformsNetworks < ActiveRecord::Migration[6.0] def change create_table :platforms_networks, force: :cascade do |t| t.string :platform_id t.string :platform_type t.string :name t.string :permalink t.b...
#Pass by reference vs Pass by value #In the first case, it is not affected as it is essentially passing by value # because of the non-mutable nature of method. However, it is 'a pass by reference' # case for the latter case due to the mutable nature of the method a = [1,2,3] b = [4,[5,6],[7,8]] c = [a,b,9,10] def n_m...
#============================================================================== # * Window_ShopInfo # finestra delle informazioni del negozio #============================================================================== class Window_ShopInfo < Window_Base # inizializzazione # @param [Game_Shop] shop def initial...
# coding: utf-8 class Agreement < ActiveRecord::Base #attr_accessible :name, :institution, :start_date, :end_date, :description, :user_id, :status belongs_to :user has_many :activity_log, :as => :attachable has_many :participants, :as => :attachable has_many :configurations, :as => :attachable has_many :c...
class Administrativo::CategoriasController < ApplicationController skip_before_action :verify_authenticity_token def save status, resp = Administrativo::CategoriasService.save(params_categoria) case status when :success then render json: resp, status: :ok when :not_found then render json: { errors: resp }, ...
class ChangeMangasTable < ActiveRecord::Migration[5.2] def change remove_column :mangas, :category_id end end
FactoryBot.define do factory :task do title {Faker::Job.title} text {Faker::Lorem.sentence} inportance {Faker::Number.between(from: 1, to: 4)} deadline {Faker::Date.forward} hour {Faker::Number.between(from: 1 , to: 12)} check {'false'} association :user association :board end end
require 'rails_helper' RSpec.describe 'book management function', type: :feature do before do @book = Book.create(title: "title", author: "author", price: 5000, genre: 5, released_at: "2020-12-05", story: "story", icon: "icon_URL") @user= User.new(name: "name", introduce: "introduce", icon: "icon_URL", admin...
class RenameSemesterIdFromCoursesToTimetableId < ActiveRecord::Migration def change rename_column :courses, :semester_id, :timetable_id end end
require File.expand_path("../spec_helper", __FILE__) describe Mote::Keys do class Author < Mote::Document include Mote::Keys attr_accessor :password key :name, :default => "Bill" key :active, :default => false key :coll, :default => [] key :position, :private => true end before do ...
# $Id$ # Proxy classes to normalize backup source classes used to store backup data. # Child classes used by ActiveRecord classes to create/update info in a consistent way # See facebook_photo_album.rb for usage example module BackupContentProxy def to_h db_attributes.inject({}) { |h, attr| h[attr] = send(attr...
class MessageBox < Product def initialize(decochar) @decochar = decochar end def use(s) puts "#{@decochar} #{s} #{@decochar}" (s.bytes.length + 4).times do |i| print @decochar end puts '' end end
cask 'font-firamono-nerd-font' do version '1.2.0' sha256 '77ffee4498e23e3215edc9ea6eefa9f10b03deb6815dc3ccb9ad3336cd478f5c' url "https://github.com/ryanoasis/nerd-fonts/releases/download/v#{version}/FiraMono.zip" appcast 'https://github.com/ryanoasis/nerd-fonts/releases.atom', checkpoint: '7dedec17cd...
module VagrantPlugins module Beaker module Provider module VSphereActions class EnsureConnection def initialize( app, env ) @app = app @logger = Log4r::Logger.new( 'vagrant_plugins::beaker::provider::vsphere_actions::ensure_connnection' ) end de...
FactoryBot.define do factory :adjustment_detail do adjustment_id { create(:adjustment) } user { create(:partner_organisation_user) } adjustment_type { "Actual" } end end
class Sprangular::InstallGenerator < Rails::Generators::Base source_root File.expand_path('../templates', __FILE__) def remove_spree_umbrella_gem gsub_file 'Gemfile', /^.*gem.["']spree["'].*\n/, '' end def remove_spree_core_engine_route gsub_file 'config/routes.rb', /^.*Spree::Core::Engine.*\n/, '' ...
class Admin::PresentationsController < Admin::AdminController before_filter :set_presentation, :only => [:edit, :update, :destroy] before_filter :load_speakers, :only => [:new, :edit] def index @presentations = Presentation.all end def new @presentation = Presentation.new() end def create @...
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 before_action :set_honeybadger_context before_action :load_projects before_action :ensure_user_has_github_token!...
require 'singleton' module CoreClients class CreateTaskListClient < RabbitmqPubSub::RpcPublisher include Singleton def initialize @pub_queue_name = 'rpc_TMC_create_task_list_request' @sub_queue_name = 'rpc_TMC_create_task_list_response' super end end end
# 01_create_vpc # called from main.rb # a part of ruby-aws-microservice # # Author: Cody Tubbs (codytubbs@gmail.com) 2017-05-07 # https://github.com/codytubbs def create_vpc(client) # Create VPC with CIDR block 10.0.0.0/16. puts 'Creating VPC with CIDR block 10.0.0.0/16...' response = client.create_vpc(c...
class FriendRequest < ApplicationRecord belongs_to :requester, class_name: :User belongs_to :reciever, class_name: :User validates :requester_id, presence: true validates :reciever_id, presence: true scope :new_request_to, -> (user) do where(reciever_id: user.id, approved: false).includes(:requester) ...
class BlogController < ApplicationController before_filter :is_logged, :load_conf # GET /blog # Show last recent blog posts HTML # ----------------------------------------------------------- def index @posts = Post.published.order('published_at DESC') end # GET /blog/:id ...
class CreateStudentsTeachers < ActiveRecord::Migration[5.1] def change create_table :students_teachers do |t| t.references :student t.references :teacher end remove_column :students, :teacher_id end end
class Admin::PeopleController < Admin::BaseController #默认使用admin模板 layout 'admin/admin' # GET /admin/people # GET /admin/people.json def index @admin_people = Admin::Person.all respond_to do |format| format.html # index.html.erb format.json { render json: @admin_people } end end ...
module AmazonRequestable def params_to_signed_request(params) endpoint = "webservices.amazon.com" request_uri = "/onca/xml" # Generate the canonical query canonical_query_string = QueryBuilder.query_string_from_hash(params) # Generate the string to be signed string_to_sign = "GET\n#{endpoin...
class Episode < ActiveRecord::Base belongs_to :season validates :title, presence: true validates :number, uniqueness: true validates_associated :season end
Rails.application.routes.draw do root "tasks#index" resources :tasks do member do get :start get :complete put :update_state end end resource :users, controller: 'registrations', only: [:create, :edit, :update] do get '/sign_up', action: 'new' end resource :users, controll...
require_relative './base' require 'tty-prompt' class Pltt::Actions::Create < Pltt::Actions::Base def run puts "New issue in project #{config['project'].green}:" prompt = TTY::Prompt.new title = prompt.ask('Enter issue title:') do |q| q.required true end description = prompt.multiline("Descri...
module Arel class Lock < Compound def initialize(relation, locked) super(relation) @locked = true == locked ? "WITH(HOLDLOCK, ROWLOCK)" : locked end end end module Arel module SqlCompiler class SQLServerCompiler < GenericCompiler def select_sql if complex_count_sql? ...
require 'minitest/reporters' require 'minitest/autorun' require_relative '../lib/WRAzureNetworkManagement' MiniTest::Reporters.use! [MiniTest::Reporters::DefaultReporter.new, MiniTest::Reporters::JUnitReporter.new] class TestWRAzureNetworkManagement < MiniTest::Test def test_availab...
class Subscription < ActiveRecord::Base attr_accessible :account_id, :plan_id, :usage, :expired_at belongs_to :account belongs_to :plan has_one :payment validates :account_id, :presence => true validates :plan_id, :presence => true after_create :renew def remaining plan.quota - usage end def...
module Enumerable # The version of the enumerable-extra library. EXTRA_VERSION = '0.2.0' alias old_map map alias old_collect collect # Returns the numeric total of the elements of +enum+, using +total+ as # an accumulator (0 by default). Raises an error if any of the elements # are non-numeric. ...
require 'test_helper' describe Vehicle do subject { Vehicle } describe "db" do specify "columns & types" do must_have_column :vin must_have_column :make must_have_column :model must_have_column(:year, :integer) end end end
class LeadsMailer < ApplicationMailer default bcc: 'rightboat911716@sugarondemand.com', cc: 'info@rightboat.com' add_template_helper BoatsHelper # for pdf add_template_helper QrcodeHelper # for pdf add_template_helper WickedPdfHelper # for pdf layout 'mailer' after_action :amazon_delivery def lead_creat...
# ex01.rb puts "Please type in as many words as you want, I will try to sort them!" answer = gets.chomp list = [] while answer != '' list.push(answer) unless answer == '' answer = gets.chomp end puts list.sort.to_s
class MicroplstsController < ApplicationController # GET /microplsts # GET /microplsts.json def index @microplsts = Microplst.all respond_to do |format| format.html # index.html.erb format.json { render json: @microplsts } end end # GET /microplsts/1 # GET /microplsts/1.json def ...
require File.expand_path('../../test_helper', File.dirname(__FILE__)) class CmsAdmin::FixturesControllerTest < ActionController::TestCase def setup super ComfortableMexicanSofa::Fixtures.export_all(cms_sites(:default).hostname) @model = Cms::Fixture.new(:name => cms_sites(:default).hostname) end def...
class CreateBusinessclaims < ActiveRecord::Migration def change create_table :businessclaims do |t| t.string :claimfname t.string :claimlname t.string :claimemail t.string :claimcontact t.string :business_type t.string :status t.integer :vendor_id t....
# encoding: utf-8 describe "group" do subject { mapper.new.call input } let(:input) do [ { name: "Joe", role: "admin", type: "job", contacts: [{ email: "joe@doe.com" }, { email: "joe@doe.org" }] }, { name: "Ian", role: "admin", type: "job",...
require 'nokogiri' require 'open-uri' module ExchangeRateJt module RatesSource class CouldNotFetchDataError < StandardError; end class ParseError < StandardError; end class ECB REPOSITORY_URL = 'http://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist-90d.xml'.freeze CURRENCY_LIST = %w(AUD BG...
require_relative '../lib/machospec' describe "Testing Framework" do describe ".should_equal" do it "don't raise an exception if its true" do exception = nil begin 4.should_equal 4 rescue => e exception = e end exception.should_be_nil end it "raises and exept...
# DOC: # We use Helper Methods for tree building, # because it's faster than View Templates and Partials # use h.html_escape(node.content) for safe content module RenderTreeHelper class Render class << self attr_accessor :h, :options def render_node(h, options) @h, @options = h,...
# 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...
class PackedEnum include Enumerable attr_reader :identifiers attr_reader :attributes attr_reader :defaults def initialize(identifiers, attributes, value = nil) self.identifiers = identifiers self.attributes = attributes @map = value ? Bitmap.new(value, @width) : default_bitmap end def [](at...
class CreateLocodes < ActiveRecord::Migration[6.0] def change create_table :locodes do |t| t.string :change_marker t.references :country, foreign_key: true t.string :city_code t.string :full_name t.string :full_name_without_diacritics t.string :alternative_full_names t.st...
class ToDo < ApplicationRecord belongs_to :collab has_many :to_do_items, dependent: :destroy end
class Verse < QuranApiRecord belongs_to :chapter, inverse_of: :verses, counter_cache: true has_many :tafsirs has_many :words has_many :translations has_many :audio_files has_many :recitations, through: :audio_files has_one :translation has_one :tafsir end
require 'mkmf-gnome2' unless required_pkg_config_package("arrow") exit(false) end unless required_pkg_config_package("arrow-glib") exit(false) end [ ["glib2", "ext/glib2"], ].each do |name, source_dir| spec = find_gem_spec(name) source_dir = File.join(spec.full_gem_path, source_dir) build_dir = source_di...
class AddPropertyCategoryIdToSpreeProductProperties < ActiveRecord::Migration def change add_column :spree_product_properties, :category_id, :integer, index: true end end
class ChangeAttachmentColumnInFileUpload < ActiveRecord::Migration[5.2] def change remove_column :file_uploads, :attachment end end
class ApplicationRecord < ActiveRecord::Base self.abstract_class = true def saque_conta(account, valor_extra=0) if not(account.veririficar_saldo_suficiente(self.valor)) errors.add(:base, "Saldo insuficiente em Conta!") throw(:abort) else account.saldo= account.saldo - (self.valor+valor_ex...
class RenameColumn < ActiveRecord::Migration[6.1] def change rename_column :tags, :tag, :title end end
class O0100a2_title attr_reader :title, :options, :name, :field_type, :node def initialize @title = "Section O: Special Treaments, Procedures and Programs" @name = "Chemotherapy: Performed in the last 14 days while a resident (O0100a2)" @field_type = RADIO @node = "O0100A2_title" ...
class Deallog < ActiveRecord::Base attr_accessible :deal_id, :description validates :deal_id, :description, :presence => true belongs_to :deal end
# ****************** CUSTOM SASS FUNCTIONS FOR TIMPLATE ****************** # puts "====== DETERMINATION ======" require "sass" require "base64" # **************************** base64Encode() **************************** # # base64Encode for easy use into data URIs # added by CHROMATIX TM 03/08/2015 # HT: http://...
class CreateProjects < ActiveRecord::Migration def self.up create_table :projects do |t| t.string :name t.date :planend t.date :planbeg t.integer :worktype_id t.integer :planeffort t.integer :employee_id t.integer :country_id t.timestamps end end def self....
require_relative "../spec_helper" describe "rbenv_script provider" do let(:runner) { ChefSpec::Runner.new(step_into: ["rbenv_script"]) } let(:node) { runner.node} context "with a fully configured resource" do let(:chef_run) { runner.converge("fixtures::rbenv_script_full") } before do u...
require "formula" class Owamp < Formula homepage "http://www.internet2.edu/performance/owamp/" url "http://software.internet2.edu/sources/owamp/owamp-3.4-10.tar.gz" sha1 "acf7502eef15fc0ac14d1b1d86e28759b4bc39fe" bottle do cellar :any sha1 "e1746058ddd62ec75ec1b62be837e22c3527c37a" => :yosemite sh...
class Addactivation < ActiveRecord::Migration def change change_table :users do |t| t.column :activation, :integer end end end
class CreateAds < ActiveRecord::Migration def self.up create_table :ads do |t| t.integer :client_id, :null => false t.decimal :price, :default => 0 t.datetime :start_time t.datetime :end_time t.string :media_file_name t.string :media_content_type t.integer :media_...
#! /usr/local/bin/ruby class String def === other puts "comparing ===" self == other end end a, b = "bla", "bla" case a #when b # puts "it's b!" when "bla" puts "it's bla!" else puts "nothing matched" end
class IntakesController < ApplicationController def create Intake.create( user_id: intake_params[:user][:id], flavor_id: intake_params[:actions][0][:value] ) show_todays_stats end private def intake_params json_params = ActionController::Parameters.new(JSON.parse(params['payload'])...
FactoryGirl.define do factory :place_update do place name 'Craftsmen Angers' kind Kind.codes.first state :pending url 'http://craftsmen.io' logo_url 'https://pbs.twimg.com/profile_images/425256684244566016/N0wcdLyQ_400x400.jpeg' twitter_name 'craftsmenhq' description 'This could be a l...
json.array!(@visit_actions) do |visit_action| json.extract! visit_action, :id, :visit_id, :user_id, :server_time, :url, :referrer_url, :page_title, :page, :entity, :subject, :total_time_on_action json.url visit_action_url(visit_action, format: :json) end
class CreateSiTfChoiceOptions < ActiveRecord::Migration def change create_table :si_tf_choice_options do |t| t.integer :si_tf_choice_id t.text :text t.boolean :true_answer t.timestamps end add_index :si_tf_choice_options, :si_tf_choice_id end end
require 'rails_helper' RSpec.describe TransactionsController, type: :controller do let(:valid_attributes) {{ amount: '100', transaction_type: 'withdraw' }} let(:invalid_attributes) {{ amount: '0', transaction_type: 'withdraw' }} let(:current_user) { User.create(first_name: 'Bill', last_name...
class EventChangeRegistrationPolicyService < CivilService::Service class Result < CivilService::Result attr_accessor :move_results end self.result_class = Result class SignupSimulator attr_reader :registration_policy, :move_results_by_signup_id, :immovable_signups, :new_signups_by_signup_id a...
module Rules def self.read(settings,key,default=nil) read!(settings,key) rescue default end def self.read!(settings,key) if key.is_a?(Array) key.each do |k| raise SettingMissing,k unless settings && settings.has_key?(k) settings = settings[k] end sett...
class SpentTime < ActiveRecord::Base attr_accessible :day, :spent_time belongs_to :task validates :task_id, :presence => true, :numericality => true validates :day, :presence => true validates :spent_time, :presence => true, :inclusion => { :in => 1..1440 }...
module Refinery module NewsItems class NewsItem < Refinery::Core::BaseModel self.table_name = 'refinery_news_items' attr_accessible :content, :title, :position, :published acts_as_indexed :fields => [:content, :title] validates :content, :presence => true, :uniqueness => true sco...
def unique_chars?(string) alphabet = ('a'..'z').to_a counter = Hash.new(0) string.each_char do |char| if alphabet.include?(char) counter[char] += 1 end end counter end p unique_chars?("computer")
Rails.application.routes.draw do devise_for :users root to: 'welcomes#index' end
class AddColorToPost < ActiveRecord::Migration def change add_column :posts, :blog_color_id, :integer, null: false end end
class Admin::VideosController < ApplicationController layout 'painel_admin' before_action :admin_logged_in? def index if params[:idcurso].present? @curso = Curso.find_by(id: params[:idcurso]) @video = Video.where(curso_id: params[:idcurso]); else redirect_to :controller => "cursos", :ac...
require 'test_helper' class ApartmentTest < ActiveSupport::TestCase def setup @apartment = apartments(:apartment1) @movement = movements(:movement1) @apartment_movement = apartment_movements(:apartment_movement1) @user_apartment = user_apartments(:user_apartment1) end test 'Apartment Model 001 -...
Given(/^I have created several jobs$/) do @user.jobs.create!([ { command: 'ls', dyno_size: 'Free', frequency: 'daily', last_run: nil, run_at: '02:30' }, { command: 'sudo rm /*', dyno_size: 'Free', frequency: 'monthly', last_run: DateTime.new(2017, 1, 1...
class LinkedList attr_accessor :head def initialize(value) @head = LinkedListNode.new(value) end def append(value) current_element = @head while current_element.next_node !=nil current_element = current_element.next_node end current_ele...
class MySignupRequestsLoader < GraphQL::Batch::Loader attr_reader :user_con_profile def initialize(user_con_profile) @user_con_profile = user_con_profile end def perform(keys) signup_request_scope = user_con_profile.signup_requests.where(target_run_id: keys.map(&:id)) signup_requests_by_run_id = s...
Rails.application.routes.draw do root 'foo#hello' get 'home' => "static_pages#home" get 'help' => "static_pages#help" get 'about' => "static_pages#about" get 'contact' => "static_pages#contact" # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html get 'signup...
class Question < ActiveRecord::Base MIN_LENGTH = 50 belongs_to :user validates_length_of :answer, :minimum => MIN_LENGTH, :maximum => 600, :allow_blank => true scope :answered, -> {where('length(answer) >= ?', MIN_LENGTH)} end
# encoding: utf-8 require "sea_battle" describe SeaBattle do let(:board) { SeaBattle::Board } # ABCDEFGHIJ # 1 * # 2 **** * # 3 # 4 * * # 5* * * # 6 * # 7 # 8 *** # 9 ** * # 10 * * let(:first_raw_board) { "1111111121" + "122221...
class Subject < ApplicationRecord has_many :pages scope :visible, lambda{where(:visible => true)} scope :invisible, lambda{where(:visible => false)} scope :sorted, lambda{order("position ASC")} scope :newest_first, lambda{order("created_at DESC")} scope :search, lambda {|query| where(["name LIKE ?", "%#{q...
class AddApproverToPr < ActiveRecord::Migration def change change_table :pull_requests do |t| t.references :approver, type: :uuid, index: true end end end
class UsersController < ApplicationController before_action :logged_in_user, :authenticate_supervisor! before_action :load_user, except: %i(index new create) def index @users = User.latest.paginate page: params[:page], per_page: Settings.user_per_page end def new @user = User.new end def ...
#!/usr/bin/env ruby require 'solidus_cmd' command = ARGV.first case command when 'extension' ARGV.shift SolidusCmd::Extension.start else fail "unknown command: #{command}" end
Rails.application.configure do # Verifies that versions and hashed value of the package contents in the project's package.json config.webpacker.check_yarn_integrity = true # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's cod...
module ActiveRecordPostgresEarthdistance module ActsAsGeolocated extend ActiveSupport::Concern included do end module ClassMethods def acts_as_geolocated(options = {}) if table_exists? cattr_accessor :latitude_column, :longitude_column self.latitude_column = options...
Rails.application.routes.draw do get "/email_sent/:id", to: "static_pages#email_sent", as: "email_sent" get "/home", to: "static_pages#home" get "/sign_in", to: "static_pages#sign_in" get "/sign_up", to: "static_pages#sign_up" resources :companies, only: [:create, :new, :show] do resources :jobs, only: [...
class AreaSerializer < ActiveModel::Serializer attributes(:id, :name, :width, :height) embed(:ids, :include => true) has_many(:players, :key => :players) end
class Deck < ApplicationRecord has_many :cards belongs_to :user validates :title, presence: true end