text
stringlengths
10
2.61M
class MatchSerializer < ActiveModel::Serializer attributes :id, :home_score, :away_score belongs_to :home_player belongs_to :away_player end
module Yaks module Serializer def self.register(format, serializer) raise "Serializer for #{format} already registered" if all.key? format all[format] = serializer end def self.all @serializers ||= {json: JSONWriter} end module JSONWriter extend Yaks::FP::Callable ...
require 'minitest_helper' describe JsonStructure::Number do describe 'without options' do it do js = build { number } assert js === -100 assert js === 0.99 refute js === [128] end end describe 'with :max option' do it do js = build { number(max: 100) } assert j...
class Updateusers < ActiveRecord::Migration def change add_column :users, :uid, :integer add_index :users, :uid end end
class Assignment < ActiveRecord::Base attr_accessible :project_id, :researcher_id belongs_to :researcher belongs_to :project validates :project_id, :presence => true validates :researcher_id, :presence => true end
module Pacer::Utils module Trie class << self def trie(graph, name) t = graph.v(self, :name => name).first if t t else graph.create_vertex self, :type => 'Trie', :name => name end end def route_conditions(graph) { :type => 'Trie' } ...
child @friend => "friends" do attributes :user_id,:first_name,:last_name,:username, :email, :status end
module Midishark class Cli def initialize(config, args = ARGV) @config = config @args = args end def run! case @args.first when 'capture' capture! when 'format' format! else abort "Unknown command: #{@args.first}" end end private ...
# # Cookbook:: firefox_configuration # Recipe:: default # # MIT def ensure_dir(path) directory path do action :create recursive true end end def create_template(source_template, path) template path do source source_template end end # Set the firefox installation base directory install_path = File...
Puppet::Type.type(:wlp_feature).provide(:ruby) do def get_installed_features begin feature_command = "#{@resource[:base_path]}/bin/productInfo" command = [feature_command, 'featureInfo'] installed_features = Puppet::Util::Execution.execute(command, :uid => resource[:wlp_user], :combine => true, ...
Pod::Spec.new do |s| s.name = 'SwiftCrypto' s.version = '0.2.0' s.license = 'MIT' s.summary = 'A simple Cryptography Implementation in Swift for the ARK Blockchain' s.homepage = 'https://github.com/ArkEcosystem/swift-crypto' s.authors = { 'Ark Ecosystem' => 'info@ark.io' } s.source = { :git => 'https://gi...
RailsDeviseRspecCucumber::Application.routes.draw do get "users/index" get "users/show" # get "home/index" # get 'users/:id', :to =>'users#index', :as => :user # resources :users, :only => [:show] # authenticated users -- those logged in and # have an account -- will see the home page # By default, De...
# Truthiness # The ability to express true and false is an important concept in any programming languages. # It is used to build conditional logic # "true" or "false" is expressed with boolean data type. # A boolean is an object whose only purpose is to convery whether it is "true" or "false" # Examples if true puts...
module Test module HumbleUnit module Outputs class FileOutput < BaseOutput require 'fileutils' def flush(test_class_name, messages, stats) content = build_header(test_class_name) content += build_content(messages, stats) create_report_directory write...
module Maestro module Util class Shell VERSION = '1.0.1' end end end
require 'nkf' class ArtistItem < ActiveRecord::Base belongs_to :artist has_many :artist_tracks has_many :users_artist_items_tags def self.find_items artist_id, page, keyword = '' artist = Artist.find artist_id search_artist = artist.name artist_alias_names = artist.artist_aliases.map{|artist_aliase|...
# Classes and Objects # objects contain states, tracked by instance variables # objects have behaviors, which are instance methods class Dog attr_accessor :weight, :name, :height @@count = 0 def self.total_dogs @@count end def initialize(name, height, weight) @name = name @height = hei...
class AdministratorsController < ApplicationController before_action :signed_in_administrator, only: [:new, :index, :show, :edit, :update, :topwaiters, :panel, :destory, :lastweektop, :alldayslong] def new @administrator = Administrator.new end def index @administrators = Administrator.all ...
#!/usr/bin/env ruby # command line tool for administering data pipeline queues # # To create queues for an app following certain models: # pipeline subscribe-app APP_NAME orders,products,users require 'thor' require 'aws-sdk' require 'iron_mq' require 'pry' class Pipeline < Thor # TODO: Kinda clunky, but the...
# # SurveyTemplatesController # class SurveyTemplatesController < ApplicationController before_action :authenticate_user! before_action :authenticate_admin before_action :set_survey_template, only: [:show, :edit, :update, :destroy] # # Render Survey Template data # def index @survey_templates = Surve...
class RemoveUserFromPost < ActiveRecord::Migration[5.0] def change remove_column :posts, :user_id, :refernces end end
require "pry" def consolidate_cart(cart) final_hash= {} cart.each do |row_hash| name= row_hash.keys[0] if !final_hash[name] final_hash[name] = row_hash[name] final_hash[name][:count] = 1 else final_hash[name][:count]+=1 end end final_ha...
require 'spec_helper' describe MenuItem do before do @site = Site.make @menu = Menu.make(:site => @site) @folder1 = Folder.make(:site => @site ) @folder2 = Folder.make(:site => @site ) @folder3 = Folder.make(:site => @site ) @folder4 = Folder.make(:site => @site ) @folder5 = Folder.make(:...
# == Schema Information # # Table name: logs # # id :integer not null, primary key # device_id :integer # actual_ip_address :string(255) # message_type :string(255) # message_data :text(255) # created_at :datetime not null # updated_at :datetime ...
class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable has_many :machines, dependent: :destroy has_many :own...
#!/usr/bin/env ruby $LOAD_PATH.unshift( File.expand_path( File.dirname( __FILE__ ) + "/../../lib/" ) ) require "command/node-history" require "configuration" require "lucie/log" require "lucie/script" Lucie::Log.path = File.join( Configuration.log_directory, "node-history.log" ) def target_node ARGV.each do |...
class REntry < ActiveRecord::Base belongs_to :r_language has_many :r_pages, through: :r_pages_to_entries end
class Instructor < ApplicationRecord has_many :students def average_student_age if students.count != 0 students.sum {|student| student.age} / students.count else 0 end end def students_sort_by_name students.sort_by {|student| student.name} en...
# frozen_string_literal: true module Queries module List class Teams < ::Queries::List::Base description 'List teams with various filters' type types[::Types::TeamType] def call(_obj, _args, ctx) super do ctx[:pundit].policy_scope ::Team.all end end end en...
# To install: # brew tap avencera/yamine # brew install yamine # # To remove: # brew uninstall yamine # brew untap avencera/yamine class Yamine < Formula version 'v0.1.0' desc "A simple CLI for combining json and yaml files" homepage "https://github.com/avencera/yamine" license "Apache-2.0" if OS.m...
# frozen_string_literal: true require_relative './../../utils/response' module Sourcescrub # Get the data from API module Models # Entity class Entity include ::Sourcescrub::Utils::Response def fields field_ids.map(&:to_sym) end def parse_response(response) dynami...
class JobsController < ApplicationController def show @job = Job.find(params[:id]) end def index @all_jobs = Job.all @jobs = Job.paginate(page: params[:page], per_page: 15).order('created_at DESC') @truncate_length = 64 @truncate_length_new = 50 end # # def new # @job = Job.new # ...
# frozen_string_literal: true require 'open3' module SystemCall ## # A class responsible for communication with command line interfaces. # # @!attribute [r] args # @return [Array] class Command attr_reader :args ## # Initializes a {Command}. # # @param args [Array] The command line ...
## Exercise 5 # The following program prints the value of the variable. Why? my_string = 'Hello Ruby World' def my_string 'Hello World' end puts my_string
class Comment < ApplicationRecord validates :body, presence: true, length: { minimum: 6, maximum: 500 } #{ within 6..500 } { in 6..500 } validates :commenter, presence: true, email: true belongs_to :article end
require 'digest/sha1' class User < ActiveRecord::Base has_many :openid_trusts, :class_name => 'UserOpenidTrust' belongs_to :group belongs_to :image has_one :info has_one :mumble delegate :rights, :to => :group delegate :forum_rights, :to => :group has_many :topics has_many :posts has_many :pass...
class CreateDayPlannerTasks < ActiveRecord::Migration def up create_table :day_planner_tasks do |t| t.string :name t.integer :interval t.datetime :last_execution t.datetime :next_execution end end def down drop_table :day_planner_tasks end end
class Micropost < ActiveRecord::Base attr_accessible :content belongs_to :user validates :user_id,presence: true validates :content,presence: true, length: {maximum: 140} default_scope order: 'microposts.created_at DESC' end
# frozen_string_literal: true class Board < SimpleDelegator attr_accessor :parent NON_BLOCKNG = /^((L*(LR)*L?\ L?(RL)*R*)|(R*(RL)*R?\ R?(LR)*L*))$/ def initialize(board_str) super(board_str) end def self.initial_board(size) new('L' * size + ' ' + 'R' * size) end def self.target_board(size) ...
class AddColumnToClub < ActiveRecord::Migration[5.1] def change add_column :clubs, :position, :string, null: false add_column :clubs, :start_time, :date add_column :clubs, :end_time, :date add_column :clubs, :content, :text add_column :clubs, :current, :boolean, default: false end end
require 'vanagon/engine/base' require 'vanagon/logger' require 'json' require 'lock_manager' LOCK_MANAGER_HOST = ENV['LOCK_MANAGER_HOST'] || 'redis' LOCK_MANAGER_PORT = ENV['LOCK_MANAGER_PORT'] || 6379 VANAGON_LOCK_USER = ENV['USER'] class Vanagon class Engine # Class to use when building on a hardware device ...
class ErrorsController < ApplicationController before_action :set_error, only: [:destroy, :edit, :update, :show] before_action :move_to_index, except: [:index, :show, :search] def index @errors = Error.includes(:user).order('created_at DESC') end def new @error = Error.new end def create @e...
class Post < ActiveRecord::Base include Votable validates :title, :author, presence: true belongs_to :author, class_name: "User" has_many :sub_posts has_many :subs, through: :sub_posts, source: :sub has_many :comments has_many( :top_level_comments, -> { wh...
lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require "kalimba/persistence/version" Gem::Specification.new do |gem| gem.name = "kalimba-redlander" gem.version = Kalimba::Persistence::Redlander::VERSION gem.authors = ["Slava Kravchenko"] ...
class Budget < ApplicationRecord belongs_to :user, optional: true has_many :transactions has_many :users, through: :transactions end
#!/usr/bin/env ruby # # Copyright:: Copyright 2016, Google Inc. All Rights Reserved. # # License:: Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.ap...
require "date" class Rental attr_reader :distance, :car, :start_date, :end_date attr_accessor :discount, :commission, :id def initialize(car, start_date, end_date, distance, discount = 0) @id = nil @car = car @start_date = DateTime.parse(start_date) @end_date = DateTime.parse(end_date) @dis...
Pod::Spec.new do |s| s.name = 'VehicleID' s.version = '0.1.0' s.summary = 'Provides utilities to identify vehicles.' s.description = <<-DESC Provides a set of utilities to help identify a vehicle. DESC s.homepage = 'https://github.com/gpancio...
class MlsLookupType < ActiveRecord::Base attr_accessible :longvalue, :attr_lookup, :attr_resource, :shortvalue, :attr_date, :value, :app_title def self.get_for_filter(resource, lookup) self .select('longvalue AS name, value AS value') .order(:longvalue) .where('attr_lookup = ? AND attr_resour...
class ChangeColumnPriority < ActiveRecord::Migration[5.1] def change rename_column :tasks, :priority, :position end end
class Admin::PagesController < ApplicationController permission_required :edit_content, :except => [ :destroy ] def index end def new @page = Page.new @page.language = Configuration['site.langs'].first if Configuration['site.langs'].size == 1 end def create @page = params[:page][:class_name].constanti...
name 'myemacs' maintainer 'Adam Edwards' maintainer_email 'adamed@opscode.com' license 'Apache 2.0' description 'Configures Emacs' long_description 'Configures Emacs' version '0.2.2' depends 'git' supports 'windows' supports 'ubuntu' supports '...
require 'test_helper' class NotifierTest < ActionMailer::TestCase test "order_received" do mail = Notifier.order_received(orders(:one)) assert_equal "EMusicStore уведомление о заказе", mail.subject assert_equal ["erofeevdn@yandex.ru"], mail.to assert_equal ["edenisn@gmail.com"], mail.from assert_...
require "minitest/autorun" require_relative '../../lib/arena/table.rb' class Table < Minitest::Test attr_reader :table def setup @table = Game::Table.new end def test_invalid_move? assert_equal true, table.invalid_move?(6,6) assert_equal true, table.invalid_move?(-1,6) end def test_valid_mov...
require 'test_helper' class AnnotationTest < ActiveSupport::TestCase test 'render json' do object_keys = [:id, :type, :attributes, :relationships] attribute_keys = [:annotation_category_id, :detail, :created_at, :updated_at] annotation = Annotation.new(entry: create(:orga), annotation_category: Annotatio...
class CheckIn < ActiveRecord::Base belongs_to :device has_many :check_in_apps end
DeviseAuthenticationApi::Application.routes.draw do devise_for :users, defaults: {format: :json}, skip: [:sessions, :passwords, :confirmations, :registrations, :unlock] # admin view user get 'admin/:authentication_token/users' => 'admin/users#show', defaults: {format: :json} # admin unlocks user account ...
#!/usr/bin/env ruby require File.join(File.dirname(__FILE__), '..', 'script', 'vp_script') require 'rubygems' require 'faster_csv' Dir.chdir RAILS_ROOT options = vp_script do |opts, options| opts.separator "" opts.on(:REQUIRED, "-f", "--file FILE", "Required file") do |f| options[:file] = f end en...
class CategoriesController < ApplicationController helper_method :near_column, :sort_column, :sort_direction def index @categories = Category.all end def show @category = Category.find(params[:id]) if params[:near].present? @businesses = @category.businesses.near(near_column, 50, :order =>...
class CreateEducationalRelationships < ActiveRecord::Migration[5.1] def change create_table :educational_relationships do |t| t.references :educational, polymorphic: true, index: { name: 'index_on_educational_type_and_id' } t.references :education_program, index: { name: 'index_on_education_program_id...
require 'date' require './action' class Rental attr_accessor :start_date attr_accessor :end_date attr_accessor :distance def initialize(id, car:, start_date:, end_date:, distance:, deductible_reduction:) @id = id @car = car @start_date = start_date @end_date = end_date @days = calc_days ...
require 'test_helper' class D2L::Dataclips::ResultTest < Minitest::Unit::TestCase def test_that_fields_are_required err = assert_raises D2L::Dataclips::Error do D2L::Dataclips::Result.from({ 'fields' => nil, 'values' => [] }) end assert_equal err.message, "'fields' is missing" end def test_tha...
require 'spec_helper' describe BillsController do login_user create_account describe "GET #edit" do it "assigns the requested bill as @bill" do bill = create(:bill, account_id: @account.id) get :edit, id: bill expect(assigns(:bill)).to eq bill end it "renders the edit template" do...
#!/usr/bin/env ruby require 'fileutils' require 'pp' require 'rubygems' require 'jira-ruby' require 'json' # prerequisite: # gem install jira-ruby # interactive script--no args needed # just run ./jira -c or ./jira -b # it'll ask for confirmation before making changes # # requires: # - `fzf` on $PATH # - $JIRA_USE...
module Navigable extend ActiveSupport::Concern included do before_action do if (content_item = request.env[:content_item]) setup_content_item(content_item) else fetch_and_setup_content_item("/#{params[:slug]}") end end end end
class CreditCompaniesController < ApplicationController before_action :set_credit_company, only: [:show, :edit, :update, :destroy] before_action :authorize_for_managing # GET /credit_companies # GET /credit_companies.json def index @credit_companies = CreditCompany.all.page(params[:page]).per(10) end ...
class Message < ApplicationRecord validates :postid, {presence: true} validates :content, {presence: true} end
require 'boxzooka/item' module Boxzooka # Request to populate Boxzooka's Item metadata from our own. class CatalogRequest < BaseRequest # List of Items collection :items, entry_node_name: 'Item', entry_field_type: :entity, entry_type: Boxzooka::Item end end
class Event < ApplicationRecord belongs_to :organizer, class_name: 'User', foreign_key: 'organizer_id' belongs_to :location has_many :tickets has_one_attached :image default_scope { order(start_date: :desc) } scope :keyword_search, -> (params) { if params[:keyword].present? joins(:location).wher...
Rails.application.routes.draw do get'projects/index' #get 'projects/dashboard' post 'projects/new' get 'dashboard', to: 'projects#dashboard' # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html root 'projects#index' end
class CreateDogWalkings < ActiveRecord::Migration[5.2] def change create_table :dog_walkings, id: :uuid do |t| t.integer :status, default: 0 t.datetime :schedule_date t.float :price t.float :duration t.decimal :latitude, { precision: 10, scale: 6 } t.decimal :longitude, { preci...
module ActiveSesame::Behaviors module Ontology def self.mimic(klass, options={}) defaults = {:repository => ActiveSesame::Repository.new, :ontology_attribute => :name} defaults.merge!(options) klass.send(:include, self) klass.repository = defaults[:repository] klass.ontology_attrib...
# # Cookbook Name:: postgresql # Provider:: default # # Author:: LLC Express 42 (info@express42.com) # # Copyright (C) 2012-2013 LLC Express 42 # # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Software"), to deal in # the Softwa...
# Copyright (c) 2011 Nick Markwell # Released under the ISC license. See LICENSE. # If this does not work properly, read the README file. require 'yaml' class VolumeConfig def self.get file = nil if File.exist?(File.join(File.dirname(__FILE__), 'config.yaml')) file = File.join(File.dirname(__FILE__), ...
require "#{ENV['CORTO_BUILD']}/common" COMPONENTS = [] if not defined? COMPONENTS task :all => :default task :default do COMPONENTS.each do |e| verbose(VERBOSE) if ENV['silent'] != "true" then sh "echo '#{C_BOLD}[ >> entering #{C_NORMAL}#{C_NAME}#{e}#{C_NORMAL}#{C_BOLD} ]#{C_NORMAL}'"...
require 'rails_helper' RSpec.describe LocationGroup, type: :model do it { should validate_presence_of(:name) } it { should belong_to(:country) } it { should have_many(:locations).through(:location_relations) } end
class Cruise < ApplicationRecord belongs_to :user belongs_to :project has_many :data has_many :equipments validates :ship, presence: :true validates :project, presence: :true validates :responsible, presence: :true validates :field, presence: :true end
=begin Copyright (c) 2019 Aspose Pty Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribu...
# -*- mode: ruby -*- # vi: set ft=ruby : Vagrant.configure(2) do |config| if Vagrant.has_plugin?("vagrant-cachier") config.cache.scope = :box end config.vm.define "paper-search-vm" do |default| ip_address = "192.168.33.20" default.vm.box = "ubuntu/trusty64" default.vm.provision "shell" do |shell...
class Admin::SermonsController < Admin::BaseController def index @sermons = Sermon.all end def show @sermon = Sermon.find(params[:id]) end def new @sermon = Sermon.new end def edit @sermon = Sermon.find(params[:id]) end def update @sermon = Sermon.find(params[:id]) if @serm...
class Merchant::BaseController < ApplicationController before_filter :authenticate_merchant! layout "merchant" end
class VoicemailResponse def initialize(incoming_call) @incoming_call = incoming_call @response = Twilio::TwiML::VoiceResponse.new end def to_s play_greeting response.record(action: RouteHelper.voicemail_store_url(incoming_call), play_beep: true) response.to_s end private attr_reader :...
class AddThemes < ActiveRecord::Migration def self.up create_table :themes do |t| t.string :name end connection.execute("INSERT INTO themes VALUES (1, 'default')") end def self.down drop_table :themes end end
require 'fileutils' require 'date' class HtmlTagParser attr_reader :html_file, :file_location, :tag attr_accessor :formatted_output_string def initialize(html_file=nil,file_location=FileUtils.pwd) begin @html_file = html_file rescue @html_file = nil end if File.basename(file_location).include?('...
# Counts the support of given ItemSets class SetCounter def initialize(baskets) @baskets = baskets @threshold = baskets.rows.length * Settings::CONFIG.support_threshold @job_queue = Queue.new end # Counts an array for item sets by checking each bucket def count_item_sets(item_sets) threaded_...
class AddVatNullProject < ActiveRecord::Migration[5.2] def change add_column :projects, :is_vat_null, :boolean end end
class ApplicationController < ActionController::Base protect_from_forgery with: :null_session respond_to :json before_action :configure_permitted_parameters, if: :devise_controller? before_action :authenticate_user private # allow for additional parameters not permitted by devise natively w...
DataMagic.load("canada.yml") Given(/^I am logged into a Canadian Account, Toggle on French Language and Navigate to Statements and Documents page$/) do visit LoginPage on(LoginPage) do |page| logindata = page.data_for(:canadian_account1) username = logindata['username'] password = logindata['password']...
# Helper module to create various cached instances for bike CSV imports class BikeCsvImporter module Cache def cached_bike_purpose(purpose) @bike_purpose_cache ||= {} @bike_purpose_cache[purpose] ||= BikePurpose.find_by_purpose purpose end def cached_bike_brand(brand, new_if_empty ...
class BECoding::Command::Left def execute(rover) rover.spin_left end end
require 'rails_helper' RSpec.describe 'devise/registrations/edit.html.erb', type: :view do describe 'when signed in' do describe 'layout integration' do before(:each) do begin_with_new_signed_in_user render template: 'devise/registrations/edit', layout: 'layouts/application' end ...
class Status < ApplicationRecord validates_presence_of :name has_many :book_users, dependent: :destroy end
# == Schema Information # # Table name: users # # id :integer(4) not null, primary key # active :boolean(1) default(TRUE) # screen_name :string(255) # email :string(255) # password :string(255) # reason_for_deactivation :...
class UpdateAllSourcesWorker include Sidekiq::Worker def perform(options = {}) Source.find_each do |source| NewsFeedUpdateWorker.perform_async( source.id, source.category.id, source.feed_url, source.feed_options ) ...
class BlockField < ApplicationRecord include ActiveModel::Validations attr_accessor :value attr_accessor :conditional_fields validates_presence_of :name validates_presence_of :text # todo test validates_uniqueness_of :marker, conditions: -> { where.not(data_type: I18n.t(:condition)) } validates_numeri...
#! /usr/bin/ruby #usage: this rb script is used to produce random string sequence(ascii) from the sequence of state # -i filename #the trans_matrix file # -p filename #the input_otrace_file # -o directory #the outputfile destination # -l number #the limit of the length of the trace # -r number #the repeat time...
class RetailerCategoriesDecorator < Draper::CollectionDecorator def get(code) categories = (object + object.map(&:children)).flatten categories.find {|category| category.code == code} end def with_children object.select{|c| c.children.any? } end end
class AddPlayerFixtureHistoriesToPlayers < ActiveRecord::Migration[5.0] def change reversible do |dir| dir.up do add_column :players, :player_fixture_histories, :json Player.all.each do |player| player.update( player_fixture_histories: HTTParty.get("https:...
# West direction class. require 'toy_robot/model/direction/base_direction' module Direction class West < BaseDirection # String representation of the direction attr_reader:dir # Initialize the direction with a string representation def initialize @dir = W end # Make a left turn ...
class Recipe < ApplicationRecord validates :name, presence: true validates :category, presence: true validates :url, presence: true, uniqueness: true validates :energy, presence: true, numericality: true validates :carbs, presence: true, numericality: true validates :fat, presence: true, numericality: true ...