text
stringlengths
10
2.61M
class Order < ApplicationRecord belongs_to :user #user is a buyer and has user_id # order has listing_id as a foreign key as listing will have one order belongs_to :listing end
# This migration comes from decidim_results (originally 20170215132624) class AddReferenceToResults < ActiveRecord::Migration[5.0] class Result < ApplicationRecord self.table_name = :decidim_results_results end def change add_column :decidim_results_results, :reference, :string Result.find_each(&:sav...
class SurveysController < ApplicationController def index @surveys = Survey.all end def show @survey = Survey.includes(:questions).find(params[:id]) end end
RailsAdmin.config do |config| ### Popular gems integration ## == Devise == config.authenticate_with do warden.authenticate! scope: :user end config.current_user_method(&:current_user) ## == Cancan == config.authorize_with :cancan ## == Pundit == # config.authorize_with :pundit ## == PaperTr...
class AddShoePhotoToShoes < ActiveRecord::Migration[5.0] def change add_column :shoes, :photo, :string end end
class Author < ApplicationRecord validates_presence_of :name has_many :author_books has_many :books, through: :author_books def average_pages books.average(:pages) end end
# Copyright:: # License:: # Description:: # Usage:: class PatternMap < ActiveRecord::Base belongs_to :user belongs_to :pattern belongs_to :patternable, :polymorphic => true acts_as_list scope: [:patternable_id, :patternable_type, :patternable_attribute] validates :position, :allow_nil => true, :numerical...
Redmine::Plugin.register :menu_mypage do name 'Menu Mypage plugin' author 'nobuyuki sanada' description 'move my_page in Top Menu to account_menu' version '0.0.1' url 'http://example.com/path/to/plugin' author_url 'http://example.com/about' Redmine::MenuManager.map :top_menu do |menu| menu.d...
require 'vanagon/platform' describe "Vanagon::Platform::Solaris10" do let(:block) { %Q[ platform "solaris-10-i386" do |plat| end ] } let(:plat) { Vanagon::Platform::DSL.new('solaris-10-i386') } before do plat.instance_eval(block) end describe "solaris10 has weird paths for gnu commands" d...
require_relative '../rails_helper' describe ArticleVersionsController do login_admin describe "GET #index" do it "populates an array of article_versions" do article = create(:article) get :index, article_id: article.id expect(assigns(:versions)).to match_array([ArticleVersion.first]) end...
class CreateProjects < ActiveRecord::Migration def self.up create_table :projects do |t| t.string :name t.text :brief t.string :client t.datetime :created_at t.string :contribution t.string :partner t.integer :cost t.integer :days t.integer :enjoyment t....
class Api::V1::MessagesController < ApplicationController before_action :get_channels def index @messages = Message.all render json: @messages end def create @message = Mesasge.create(message_params) render json: @message end private def get_channels @channels = Channel.all end ...
module MatchEvent class YellowCard < Base def add_info_from_match_data(match_data, current_event_string, side) return if player1.try(:name).blank? #TODO: handle the error properly somehow self.info = '2nd yellow' if match_data["#{side}_#{self.class.match_data_hash_key}"].occurrences(player1.try(:name...
class ProjectSerializer < ActiveModel::Serializer belongs_to :user attributes :id, :name, :description, :user, :columnOrder end
class Policy < ActiveRecord::Base has_many :users def virus_destiny=(destiny) self.virus_lover = (destiny == "label" ? "Y" : "N"); self.discard_viruses = (destiny == "discard" ? "Y" : "N"); end def virus_destiny return 'label' if self.virus_lover return 'discard' if self.discard_...
require 'spec_helper' describe EventDictionary do describe "#event_data_query_sql" do before do @ed_name = "ed_1" @ed2_name = "ed_2" @paired_sql = %(select s.id subject_id, s.subject_code subject_code, max( decode(e.name, '#{@ed_name}', e.id)) first_event_id, ...
class Pub attr_reader :name,:till, :drunkenness_limit def initialize(name,till,drinks, foods) @name = name @till = till @drinks=drinks @foods=foods @drunkenness_limit=5 end def increase_till(amount) @till += amount end def count_drinks return @drinks.count end def decrease...
class Category < ActiveRecord::Base has_many :portfolios has_many :subcategories end
Fabricator :category do title { Forgery::LoremIpsum.word } end
class Orderline < ActiveRecord::Base belongs_to :order, dependent: :destroy belongs_to :product, dependent: :destroy belongs_to :seller, class_name: "User" end
class Post < ApplicationRecord belongs_to :user validates :title, :content, presence: true validates_length_of :title, minimum: 10, message: 'Title must be atleast 10 characters long' end
class AddLonlatToTrip < ActiveRecord::Migration[5.0] def change add_column :trips, :start_lonlat, :st_point, geographic: true end end
# frozen_string_literal: true require 'spec_helper' require 'xero_exporter/export' require 'xero_exporter/proposal' module XeroExporter RSpec.describe XeroExporter::Proposal do context '#invoice_lines' do context 'with an example set of data' do before do export = Export.new e...
class MotionBlitzDemoManager attr_writer :progress def numberOfSectionsInTableView(table_view) 1 end def tableView(table_view, numberOfRowsInSection: section) demos.count end def tableView(table_view, cellForRowAtIndexPath: index_path) table_view.dequeueReusableCellWithIdentifier('BlitzDemoCe...
MRuby::Gem::Specification.new('mruby-system-exit') do |spec| spec.licenses = ["MIT"] spec.authors = ["Nathan Ladd"] spec.summary = "SystemExit and abort backfill" spec.homepage = "https://github.com/test-bench/mruby-ruby-compat" end
class CreditCard < ActiveRecord::Base belongs_to :customer belongs_to :address validates_presence_of :first_name, :last_name validates_format_of :number, :with => /^\d{13,18}$/ #validates_format_of :cvc, :with => /^\d+$/ validates_numericality_of :month, :only_integer => true validates_numericality_of ...
# frozen_string_literal: true class AddRegistrationQuotaToAttendance < ActiveRecord::Migration[4.2] def change add_reference :attendances, :registration_quota, index: true end end
Given /^two duplicate accounts$/ do @dup_account = Factory(:account, :id => 1, :name => "Test Account One", :phone => "1111-1111", :fax => "(111)1111111111", ...
# frozen_string_literal: true require 'spec_helper' require 'bolt_spec/integration' require 'bolt_spec/conn' describe "Passes the _task metaparameter" do include BoltSpec::Integration include BoltSpec::Conn let(:modulepath) { File.join(__dir__, '../fixtures/modules') } let(:config_flags) { %W[--format js...
# app.rb require 'sinatra' require 'sinatra/activerecord' require './environments' # Model class Score < ActiveRecord::Base validates :meters, presence: true, numericality: true validates :user_name, presence: true validates :user_gc_id, presence: true end # Welcome get "/" do "Only true Marathon He...
class Helper def initialize(browser, name) # what is this for? @browser = browser @name = name end def close @browser.close end def take_screenshot(name) path << "#{Dir.pwd}/results/#{@name} #{name}.png" b.screenshot.save(path) end def element(args, options={}) options = {:wai...
class Downloader::DirectoryHandler < Downloader::AbstractHandler def cfs_directory CfsDirectory.find(parameters[:cfs_directory_id]) end def export_request_message(recursive: false) export_request_message_template.tap do |h| h[:zip_name] = File.basename(cfs_directory.path) h[:client_id] = "di...
# code your #valid_move? method here def valid_move?(board,position) if !position.is_a? Integer if !position.match(/^\d$/) return false end end position = position.to_i if(position>=1 && position<=board.length && !position_taken?(board,position)) return true end return false end # re-de...
require 'yt/collections/base' require 'yt/models/resumable_session' module Yt module Collections # @private # Provides methods to upload videos with the resumable upload protocol. # # Resources with resumable sessions are: {Yt::Models::Account accounts}. # # @see https://developers.google.com...
# an argument is an input to a method # methods can have one or more input but it's not required # params are the specific argument given to a method def praise_person(name, age) puts "#{name.capitalize} is amazing." puts "#{name.capitalize} is charming." puts "#{name.capitalize} is talented." puts "His age is...
# here we get the coins with all their informations # linked to the current user class CoinsController < BaseController before_action :authenticated? def show market_coin = MarketCoinHandler.new(coin_ids: coin_id).refresh_and_fetch.take render json: coins_hash([market_coin]).first end def search m...
class User < ActiveRecord::Base authenticates_with_sorcery! attr_accessible :first_name, :last_name, :email, :password validates :first_name, :last_name, :email, presence: true validates :email, uniqueness: true has_many :referrals end
class String def titleize self.gsub(/\b('?[a-z])/) { $1.capitalize } end end class Pattern @@all = Array.new attr_accessor :name attr_accessor :matchers attr_accessor :values attr_accessor :matched attr_accessor :formatters def self.all @@all end def initialize(name, &block) @name...
FactoryBot.define do factory :user do name { Faker::Name.first_name } email { Faker::Internet.safe_email } password { 'password123' } factory :doctor do association :role, factory: :doctor_role end factory :patient do association :role, factory: :patient_role end end end
require 'rest-client' require 'json' require 'date' require 'csv' require 'yaml' CONFIG = YAML.load_file('./secrets/secrets.yml') date = Date.today-1 file_date = date.strftime("%Y%m") csv_file_name = "crashes_#{CONFIG["package_name"]}_#{file_date}.csv" system({"BOTO_PATH"=>"./secrets/.boto"}, "gsutil/gsutil cp gs:/...
# frozen_string_literal: true RSpec.describe Reader do let(:file_path) { 'spec/fixtures/files/sample_file.log' } subject { described_class.new(file_path: file_path) } describe '#call' do it 'calls proc for each file line' do sample_proc = proc {} expect(sample_proc).to receive(:call).with("/sa...
require 'navigasmic/builders/images_builder' require 'navigasmic/builders/breadcrumbs_builder' Navigasmic.setup do |config| # Defining Navigation Structures: # # You can begin by defining your navigation structures here. You can also define them directly in the view if you'd # like, but it's recommen...
class CartsController < ApplicationController before_action :logged_in_user def index @cart = current_cart @cart_details = @cart.cart_details end def destroy @cart = current_cart @cart_details = @cart.cart_details.find_by id: params[:id] @cart_details.destroy @cart_details = @cart.cart_...
require 'spec_helper' describe Crepe::Middleware::JSCallback do app do get '*catch' do error! :not_found end end before { get '/anywhere', callback: 'say' } it 'renders JavaScript callback' do expect(last_response.body).to eq( '%{function}(%{body},%{headers},%{status})' % { f...
# frozen_string_literal: true require 'waterdrop' require 'ruby-progressbar' require_relative 'config' class WaterDropSetup def initialize WaterDrop.setup do |config| config.deliver = true config.kafka.seed_brokers = %w[kafka://localhost:9092] end end def publish(topic, iterations) prog...
json.name @category.name json.array do json.array! @category.products, :name, :id end
require 'rails_helper' RSpec.describe Product, type: :model do it 'has a working factory' do expect(build(:product)).to be_valid end describe 'validations' do it 'can be stored with valid attributes' do expect { create(:product) }.to change(Product, :count).by 1 end context 'cannot be sto...
module Zertico class Service module InstanceMethods def index instance_variable_set("@#{interface_name.pluralize}", resource_source.all) end def new instance_variable_set("@#{interface_name}", resource_source.new) end def show(params) instance_variable_set("...
class ItemTypeImport attr_reader :account def initialize(account) @account = account end def import(row) return unless valid?(row) item_type = create(row) item_types[item_type.name] = item_type if item_type.persisted? create_variants(item_type, row) if item_type.persisted? end def val...
# This file is copied to spec/ when you run 'rails generate rspec:install' ENV['RAILS_ENV'] ||= 'test' require 'spec_helper' require File.expand_path('../../config/environment', __FILE__) require 'rspec/rails' ActiveRecord::Migration.maintain_test_schema! DEFAULT_TITLE = 'Test title'.freeze DEFAULT_CONTENT = 'Test co...
require 'spec_helper' describe Kuhsaft::SitemapsController, type: :controller do describe '#index' do before do @page = FactoryGirl.create(:page) end it 'should be able to send a xml file' do get(:index, use_route: :kuhsaft, format: 'xml') end end end
json.array!(@comments) do |comment| json.(comment, :id, :details, :user_id) json.liking_user_ids(comment.liking_user_ids) end
# words must be 20 letters or less. and words are only letters. # words are seperated by 1 or more spaces # the last word ends with 0 or more spaces with a period. # musts print each word one at a time def odd_words(str) raise ArgumentError if str.split.any? { |word| word.length > 20} raise ArgumentError unless st...
class SearchTermsToRefineryAccommodations < ActiveRecord::Migration def change add_column :refinery_accommodations, :inclusion, :text add_column :refinery_accommodations, :exclusion, :text end end
class MyClassroomPolicy < Struct.new(:user, :my_classroom) def index? user.has_role? :student end end
# frozen_string_literal: true source "https://rubygems.org" #git_source(:github) {|repo_name| "https://github.com/#{repo_name}" } # gem "rails" gem 'wdm', '>= 0.1.0' if Gem.win_platform? # gem "jekyll" group :jekyll_plugins do ### Set default layout ### Ref: https://github.com/benbalter/jekyll-defaul...
# Numbers to Commas Solo Challenge # I spent [] hours on this challenge. # Complete each step below according to the challenge directions and # include it in this file. Also make sure everything that isn't code # is commented in the file. # 0. Pseudocode # What is the input? #input will be an integer # What is t...
class VenhiclesController < ApplicationController before_action :set_venhicle, only: [:show, :update, :destroy] rescue_from ActiveRecord::RecordNotFound, with: :not_found # GET /venhicles def index @venhicles = Venhicle.all render json: @venhicles end # GET /venhicles/1 def show render jso...
begin require 'rspec/core/rake_task' RSpec::Core::RakeTask.new(:spec) desc 'Run the tests' task :default => :spec desc 'Run the suite of tests in a docker container.' task :runtests => [:build] do sh 'docker run -it amatar/dungeon rake' end rescue LoadError puts 'You need to have the rspec gem in...
class Admin::OrdersController < ApplicationController layout "admin" after_filter :create_title, :except => [:index] def index @orders = Order.all respond_to do |format| format.html {create_title}# index.html.erb format.json { render json: @orders } end end # GET /abouts/1 ...
class ExamRoom::EmqStem < ActiveRecord::Base belongs_to :emq, :class_name => "ExamRoom::Emq", :validate => true belongs_to :answer, :class_name => "ExamRoom::EmqAnswer", :validate => true validates :emq, :presence => true validates :answer, :presence => true accepts_nested_attributes_for :answer, :reject...
require 'sinatra/base' module Sinatra module UserHelpers def gravatar_url(user) hash = Digest::MD5.hexdigest(user.email) return "http://www.gravatar.com/avatar/#{hash}" end def followers_list_cache_key "followers/#{user.cache_key}" end def followings_list_cache_key "foll...
class Vehicletable < ActiveRecord::Migration def change create_table :vehicles do |t| t.text :vehicle_no t.text :Model_name t.integer :customer_id t.timestamps end end end
class PollsController < ApplicationController def index @polls = Poll.paginate(page: params[:page]) end def show @poll = Poll.find(params[:id]) @options = @poll.option end def new @poll = Poll.new end def create @poll = Poll.create!( id: Poll.last.id + 1, content: params[...
# encoding: utf-8 require 'rails/generators' require 'rails/generators/migration' module HasHistory class InstallGenerator < Rails::Generators::Base desc "Copies a config initializer to config/initializers/has_history.rb and creates a migration file" include Rails::Generators::Migration source_root File....
fragment 'openstack_github_cookbooks' do every_node true berkshelf Hash[ %w(bare-metal data-processing integration-test object-storage orchestration telemetry block-storage common compute dashboard identity image network ...
require 'erb' require 'codebreaker' require_relative './action' class Racker def self.call(env) new(env).response.finish end def initialize(env) @request = Rack::Request.new(env) @request.session['start'] = true @action = Action.new(@request) end def response case @request.path when...
class RiggersController < ApplicationController http_basic_authenticate_with :name => "posadmin", :password => "W=rcopto", :except => [:index, :show] # GET /riggers # GET /riggers.json def index @riggers = Rigger.all respond_to do |format| format.html # index.html.erb format.json { render...
require 'spec_helper' require_relative '../lib/flecha_lexer' describe 'Flecha Lexer' do shared_examples 'no se genera ningún token' do it 'no se genera ningún token' do tokens = FlechaLexer.new.lex(string) expect(tokens.size).to eq(1) # EOS Token siempre se genera. end end shared_examples '...
require 'promotion_multibuy' describe PromotionMultibuy do let(:multibuy) { PromotionMultibuy.new } let(:basket) { double :basket } let(:item) { double :item } before :each do multibuy.set_discount( item: item, quantity: 2, discount_price: 3 ) allow(basket).to receive(:number_held).twice.and_return(2...
# Print all redraw and input events to stdout. # # You can exit the example by hitting `<esc>:qa!<enter><enter>` # (as if you were exiting vim, plus an additional `<enter>`) # require "neovim/ui" Neovim.ui do |ui| ui.dimensions = [10, 10] ui.backend do |backend| backend.attach_child(["nvim", "-u", "NONE"]) ...
# frozen_string_literal: true require 'sequel' module IndieLand module Database # Object-Relational Mapper for Events class CommentOrm < Sequel::Model(:comments) plugin :timestamps, update_on_create: true end end end
module Fact module Specificity class Venue < Base HOME = :home AWAY = :away attr_accessor :venue def initialize(venue) raise "Invalid Venu" if ![HOME, AWAY].include?(venue) self.venue = venue end def get_data_scope(fact) case venue when HOME ...
require "#{File.dirname(__FILE__)}/../test_helper" require 'rack/less/config' class ConfigTest < Test::Unit::TestCase context 'Rack::Less::Config' do setup do @config = Rack::Less::Config.new end { :cache => false, :compress => false, :combinations => {}, :combination_timesta...
class ParticipationsController < PlatformController before_action :authenticate_participant before_action :check_managed_account, only: [:edit] def create @study = Study.find(params[:participation][:study_id]) if @study.full? flash[:error] = 'Sorry, this study has reached its maximum number of '\ ...
# For using the ldap service to lookup memberships and user info module LdapableHelper # this was developed using guidence from this gist: # https://gist.githubusercontent.com/jeffjohnson9046/7012167/raw/86587b9637ddc2ece7a42df774980fa9c0aac9b3/ruby-ldap-sample.rb # require 'rubygems' # require 'net/ldap' #...
class OrderDistribution include ActiveModel::Model attr_accessor :postal_code, :city, :prefecture_id, :building_name, :address, :phone_number, :user_id, :item_id, :token with_options presence: true do validates :postal_code, format: { with: /\A\d{3}-\d{4}\z/ } validates :city validates :address v...
def load_and_extend_graph_from_file(filename) session = Tensorflow::Session.new graph = Tensorflow::Graph.new graph.read(File.join(File.dirname(__FILE__), '..', 'example_graphs', filename)) session.extend_graph(graph) session end
# frozen_string_literal: true require 'rails_helper' describe 'V1::BoardsController PUT update', type: :request do let(:original_name) { 'New Test Board' } let(:new_name) { 'Not the original name' } let(:board) { create(:board, name: original_name) } let(:params) { { board: { name: new_name, format: :json } }...
namespace :forte_manager do desc 'import all transactions from forte' task :import_transactions => :environment do ForteManager::Importer.new( resource: 'transactions', model: ForteManager::Transaction, id: :transaction_id ).call end desc 'update transactions from last 10 days' task...
require 'spec_helper' describe GnipInstancePresenter, :type => :view do let(:gnip_instance) { gnip_instances(:default) } let(:user) { gnip_instance.owner } let(:presenter) { GnipInstancePresenter.new(gnip_instance, view, options) } let(:options) { {} } describe "#to_hash" do let(:hash) { presenter.to_ha...
class AddCurrentDeviceToUsers < ActiveRecord::Migration def change add_column :users, :current_device_id, :integer, unique: true end end
require 'puppet/purestorage' Puppet::Type.type(:pure_volume).provide(:rest) do desc "Pure FlashArray volume provider using REST API" mk_resource_methods def array_host end def self.instances # TODO: Implement this? super() end def initialize(value={}) super(val...
class ProductService class << self include ApiClientRequests def build(json) results = json.respond_to?(:body) ? json.body : json if results.kind_of?(Array) results.collect { |result| Product.new result } elsif results.has_key? :facets products = results.delete(:results).col...
cask 'font-twitter-color-emoji' do version '1.3' sha256 '832668d16a8aa79b4c3202f4b0e080e786aa302682abf29a1be4ab908187d520' url "https://github.com/eosrei/twemoji-color-font/releases/download/v#{version}/TwitterColorEmoji-SVGinOT-#{version}.zip" appcast 'https://github.com/eosrei/twemoji-color-font/releases.ato...
class QuestionsController < ApplicationController before_action :check_if_logged_in, except: [:index, :show] before_action :check_if_owner, only: [:edit, :update, :destroy] before_action :get_question, only: [:show, :edit, :update, :destroy, :add_reply] def new @question = Question.new end def cre...
class CreateProductQuestions < ActiveRecord::Migration def self.up create_table :product_questions do |t| t.column :category_id, :integer, :null => false t.column :kind, :enum, ProductQuestion::KIND_DB_OPTS t.column :label, :string, :null => false, :limit => ProductQuestion::LABEL_MAX_LENGT...
class CreatorsController < ApplicationController def index @creators = Creator.all.order('id asc') end def show @creator = Creator.find(params[:id]) end def create @creator = Creator.new(creator_params) respond_to do |format| if @creator.save format.json { render json: @creato...
class ProcessedTransaction < ActiveRecord::Base belongs_to :list validates :list_id, presence: true, uniqueness: true validates :transaction_id, presence: true, uniqueness: true end
# Custom SASS extension to provide a way to output # some SASS variable settings to a javascript file. # You can then use this in your javascript. require 'compass' require 'json' extension_path = File.expand_path(File.join(File.dirname(__FILE__), "..")) Compass::Frameworks.register('sasstojs', :path => extension_pat...
require_relative '../test_helper' class BounceTest < ActiveSupport::TestCase def setup super Bounce.destroy_all end test "should create bounce" do assert_difference 'Bounce.count' do create_bounce end end test "should not create duplicate bounce" do assert_difference 'Bounce.count...
require 'rails_helper' RSpec.describe TravelPlan::Edit do let(:op) { described_class } let(:lhr) { create(:airport, name: 'Heathrow', code: 'LHR') } let(:jfk) { create(:airport, name: 'JFK', code: 'JFK') } let(:account) { create_account } let(:plan) do create_travel_plan( account: account, ...
require_relative '../../spec_helper' describe 'default recipe on ubuntu 14.04' do let(:chef_run) { ChefSpec::SoloRunner.new(platform: 'ubuntu', version: '14.04').converge('webapp-java::default') } it 'converges successfully' do expect { :chef_run }.to_not raise_error end it 'creates a user with the defau...
module StormFury::CLI class Servers < Resource def create # -m metadata # -e environment # -h host # -n deployment name domain = options[:domain] name = args.first host = [name, domain].join('.') attributes = {}.tap do |attrs| [:flavor_id, :image_id, ...
require_relative 'player' class ComputerPlayer < Player attr_reader :moves def initialize @moves = ["rock", "paper", "scissors"] end def decide_move self.move = moves.sample end private attr_writer :move end
# We need to do this because of the way integration loading works require "rack/timeout/base" unless defined?(Rack::Timeout) # This integration is a good example of how to change how exceptions # get grouped by Sentry's UI. Simply override #raven_context in # the exception class, and append something to the fingerprin...
class ChangesToMyModelts7nxa < ActiveRecord::Migration def self.up change_column :my_models, :name, :string, :limit => 40 end def self.down change_column :my_models, :name, :string end end
require_relative('../db/sql_runner') require_relative('dives.rb') class Schedule attr_reader :id, :dive_id attr_accessor :timing, :day, :empty_boat_spaces def initialize(options) @id = options['id'].to_i @dive_id= options['dive_id'].to_i @timing = options['timing'] @day = options['day'] @...
class EndorsementsController < ApplicationController def create @review = Review.find(params[:review_id]) @restaurant = @review.restaurant @review.endorsements.create redirect_to restaurant_path(@restaurant) end end
module PokerHelp class Game #poker sessions sometimes change the game every round, or every few rounds, with the same players #a game should encapsulate card dealing and placement logic, validity rules and decision options #(though outside of draw poker decisions are usuaully just bet/check/fold/raise, w/...