text stringlengths 10 2.61M |
|---|
class EssayDetail::Header
include RailsHelpers
delegate :title, :author, to: :essay
attr_accessor :essay
def self.render(essay)
self.new(essay).render
end
def initialize(essay)
@essay = essay
end
def author
helpers.raw "By #{helpers.link_to(@essay.author, "#author_biography")}"
end... |
class Api::PasswordsController < ApplicationController
respond_to :json
def create
@user = User.send_reset_password_instructions(password_params)
respond_with(:api, @user)
end
private
def password_params
params.require(:user).permit(:email)
end
end |
require "goon_model_gen"
require "goon_model_gen/converter/abstract_conv"
module GoonModelGen
module Converter
class ResultConv < AbstractConv
class << self
# @return [String, boolean, boolean] func, requires_context, returns_error
def load_func(props)
if f = props['filter']
... |
module Api
module V1
class PostsController < ApplicationController
def index
if user_signed_in?
render json: current_user.posts
else
render json: {}, status: 401
end
end
def create
if user_signed_in?
if post = current_user.posts... |
require 'test_helper'
module AuthForum
class LineItemsControllerTest < ActionController::TestCase
setup do
@routes = Engine.routes
@user = FactoryGirl.create(:user, :name => 'nazrul')
sign_in @user
@cart = FactoryGirl.create(:cart)
@product = FactoryGirl.create(:product, :price => 2... |
# Stack - a stack has a last in first out structure
class Stack
def initialize()
@stack = Array.new
end
#this method adds an item to the stack
def add(value)
@stack.push(value)
end
# this method removes and item from the stack.
def remove
@stack.pop
end
end
my_stack = Stack.new()
p "Addi... |
require 'spec_helper'
describe Immutable::Set do
[
[:sort, ->(left, right) { left.length <=> right.length }],
[:sort_by, ->(item) { item.length }],
].each do |method, comparator|
describe "##{method}" do
[
[[], []],
[['A'], ['A']],
[%w[Ichi Ni San], %w[Ni San Ichi]],
... |
class FilterTypesController < ApplicationController
layout 'admin'
# GET /filter_types
# GET /filter_types.json
def index
@filter_types = FilterType.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @filter_types }
end
end
# GET /filter_types/1
#... |
require 'rspec'
class Foo
def nico
"nico"
end
end
class String
def ellipsify(number)
'hola m...'
end
end
describe 'Extender strings con ellipsify' do
it 'extender string' do
"hola mundo".ellipsify(6).should == "hola m..."
end
it 'instanciar nico' do
foo = Foo.new
foo.nico.should... |
# encoding: utf-8
MONTHNAMES_IN_PORTUGUESE = [nil] + %w{Janeiro Fevereiro Março Abril Maio Junho Julho Agosto Setembro Outubro Novembro Dezembro}
Date::DATE_FORMATS[:portuguese] = lambda{|date| date.strftime("%Y, %d de #{MONTHNAMES_IN_PORTUGUESE[date.month]}")}
|
Pod::Spec.new do |spec|
spec.name = 'PendingBusinessCore'
spec.version = '0.1.0'
spec.homepage = 'https://github.com/AMoraga/PendingBusinessCore'
spec.authors = { 'amoraga' => 'hello@albertomoraga.com' }
spec.summary = 'Core of PendingBusiness.'
spec.source = { :git => 'http... |
class BillAnalyzer
def self.calculate_balance(bills)
not_deleted_bills = bills.select { |bill| !bill.is_deleted }
balance = 0
not_deleted_bills.each do |bill|
if bill.is_expense
balance -= bill.amount
else
balance += bill.amount
end
end
balance
end
#Return a... |
require 'oauth2'
module Gateway
class Quickbook < Result
attr_reader :api
attr_accessor :consumer, :access_token, :company_id
module HTTP
JSON = "application/json"
end
module ENVIRONMENT
SANDBOX = "sandbox"
PRODUCTION = "production"
end
module API... |
# frozen_string_literal: true
Class.new(Nanoc::DataSource) do
identifier :release_notes
def items
return [] unless defined?(Bundler)
# content
path = Bundler.rubygems.find_name('nanoc').first.full_gem_path
raw_content = File.read("#{path}/NEWS.md")
content = raw_content.sub(/^#.*$/, '') # rem... |
require "net/http"
require "json"
class Events
attr_reader :state, :city, :events
def initialize(geolocation)
@state = geolocation.region_code
@city = geolocation.city
@events = get_events
end
def uri
uri = URI("https://api.seatgeek.com/2/events?venue.state=#{@state}&venue.city=#{@city}")
en... |
require 'set'
require 'cassandra_object/log_subscriber'
require 'cassandra_object/types'
module CassandraObject
class Base
class << self
def column_family=(column_family)
@column_family = column_family
end
def column_family
@column_family ||= base_class.name.pluralize
en... |
require_relative '../test_helper'
class LoginActivityTest < ActiveSupport::TestCase
def setup
super
require 'sidekiq/testing'
Sidekiq::Testing.inline!
end
test "should create login activity" do
assert_difference 'LoginActivity.count' do
create_login_activity
end
end
test "should... |
#!/usr/bin/env ruby
require 'spec_ovz'
require "test/unit"
module OpenNebula
class IMOpenVZTest < Test::Unit::TestCase
def test_parse_cpu_power
text = File.read("test/resources/vzcpucheck.txt")
current_cpu_utilization, node_cpu_power = IMOpenVZParser.parse_cpu_power(text)
assert_equal "4000",... |
Rails.application.routes.draw do
get '/sign_up' => 'users#new', as: 'sign_up'
get '/sign_in' => 'sessions#new', as: 'sign_in'
delete '/sign_out' => 'sessions#destroy', as: 'sign_out'
root 'home#welcome'
resources :users
resources :sessions
resources :password_resets
end
|
class RawMaterialsController < ApplicationController
# GET /raw_materials
# GET /raw_materials.xml
def index
@raw_materials = RawMaterial.all
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @raw_materials }
end
end
# GET /raw_materials/1
# GET /raw_... |
class Entry
attr_reader :name, :size
def initialize(name, size)
@name = name
@size = size
end
def add(entry)
end
def print_list(prefix)
end
def to_string
"#{name} (#{size})"
end
end
|
require 'spec_helper'
describe SysModule do
it "should be OK" do
m = FactoryGirl.build(:sys_module)
m.should be_valid
end
it "should reject nil module name" do
m = FactoryGirl.build(:sys_module, :module_name => nil)
m.should_not be_valid
end
it "should reject nil module group name" do
... |
require 'test_helper'
class HotelsControllerTest < ActionDispatch::IntegrationTest
setup do
@hotel = hotels(:one)
end
test "should get index" do
get hotels_url, as: :json
assert_response :success
end
test "should create hotel" do
assert_difference('Hotel.count') do
post hotels_url, pa... |
require 'send_recover_link'
describe SendRecoverLink do
let(:user){double :user, email: "test@test.com", token: "12345678"}
let(:mail_gun_client){double :mail_gun_client}
before do
allow(Mailgun::Client).to receive(:new).and_return(mail_gun_client)
end
it "sends a message to mailgun when it is called" ... |
# frozen_string_literal: true
require 'test_helper'
class UserLogoutTest < ActionDispatch::IntegrationTest
test 'users get logged the fuck out when they want' do
@user = users(:michael)
get login_path
post login_path, params: { session: { email: @user.email, password: 'password' } }
delete logout_p... |
class Importers::TXT::Mapper::TopicQ < Importers::TXT::Mapper::Instrument
def import(options = {})
cc_question_ids_to_delete = @object.cc_questions.pluck(:id)
set_import_to_running
@doc.each do |q, t|
log :input, "#{q},#{t}"
qc = @object.cc_questions.find_by_label q
topic = Topic.find_by... |
class BankAccount
@@account_count = 0
def initialize
@account_no = random_string(8)
@savings_balance = 0
@checking_balance = 0
@@account_count += 2
@interest_rate = 0.01
end
def self.show_account_count
puts "Total number of accounts: #{@@account_count}"... |
class RenameEffectiveOn < ActiveRecord::Migration
def self.up
rename_column :notes, :effective_on, :related_date
end
def self.down
rename_column :notes, :related_date, :effective_on
end
end
|
require 'spec_helper'
module Dbmanager
module Adapters
module Mysql
describe Dumper do
before { Dbmanager.stub :output => STDStub.new }
let :source do
Environment.new(
:username => 'root',
:ignoretables => ['a_view', 'another_view'],
:datab... |
class VictimZombie < ActiveRecord::Base
belongs_to :victim
belongs_to :zombie
end |
require_dependency "fastengine/application_controller"
module Fastengine
class ParticlesController < ApplicationController
before_action :set_particle, only: [:show, :edit, :update, :destroy]
# GET /particles
def index
@particles = Particle.all
end
# GET /particles/1
def show
end
... |
require "uri"
class InputProcessing::StreamProxy
def initialize(input_string)
@input_string = input_string
@ios = nil
determine_source
end
def get_line
@ios.gets
end
private
def determine_source
if input_is_file_path?
@ios = InputProcessing::FileStream.new(format_file_path).get... |
require 'rails_helper'
describe TwilioService do
describe 'proxy configuration' do
it 'ignores the proxy configuration if not set' do
expect(Figaro.env).to receive(:proxy_addr).and_return(nil)
expect(Twilio::REST::Client).to receive(:new).with('sid', 'token')
TwilioService.new
end
it ... |
require 'rails_helper'
require 'users_helper'
include SessionsHelper
# Specs in this file have access to a helper object that includes
# the UsersHelper. For example:
#
# describe UsersHelper do
# describe "string concat" do
# it "concats two strings with spaces" do
# expect(helper.concat_strings("this","t... |
require 'test_helper'
class EmployeesControllerTest < ActionDispatch::IntegrationTest
def setup
@employee = employees(:one)
end
test "should redirect update when not logged in" do
patch employee_path(@employee), params: { employee:
{ first_name: @employee.first_name, last_name: @employee.last_na... |
require_relative '../../test_helper'
class SmoochCapiTest < ActiveSupport::TestCase
def setup
WebMock.disable_net_connect! allow: /#{CheckConfig.get('storage_endpoint')}/
RequestStore.store[:smooch_bot_provider] = 'CAPI'
@config = {
smooch_template_namespace: 'abcdef',
capi_verify_token: '1... |
require "optparse"
module RPCBench
class Options
MODE_VALUES = ['rabbitmq', 'stomp', 'zeromq', 'grpc', 'nats']
OPT_DEFAULT = {
:host => 'localhost',
:port => 5672,
:mode => 'rabbitmq',
}
def initialize
def sets(key, short, long, desc)
@opt.on(short, long, desc) {|v| @... |
class RemoveAnnotatableFromAnnotation < ActiveRecord::Migration[5.0]
def change
remove_reference(:annotations, :annotatable, index: true)
end
end
|
require 'rtlog'
require 'erb'
require 'fileutils'
module Rtlog
class Page
include ERB::Util
attr_reader :config
attr_reader :log
attr_writer :logger
def initialize config, log
@config = config
@log = log
end
def logger
defined?(@logger) ? @logger : Rtlog.logger
end
def con... |
require 'active_support/concern'
module SimpleMachinable
extend ActiveSupport::Concern
class SimpleBlueprint < Machinist::Blueprint
def make!(attributes={})
make(attributes).tap(&:save!)
end
end
included do
extend Machinist::Machinable
# ClassMethods is included *before* the included bl... |
class UnitTestSetup
def initialize
@name = "Test::Spec"
super
end
VERSION = '0.10.0'
def require_files
if defined?(RUBY_ENGINE) && RUBY_ENGINE == 'ironruby'
require 'test/ispec'
else
require 'rubygems'
gem 'test-spec', "=#{VERSION}"
end
end
def gather_files
@... |
# -*- encoding : utf-8 -*-
require "rubygems"
require 'bundler/setup'
require "yaml"
require_relative "irc_connector"
require_relative "module_handler"
YAML::ENGINE.yamler = 'syck'
class Bot
attr_accessor :nick, :connected, :base_path, :module_config
def initialize(config_file, module_handler)
@config_file ... |
class DrugsController < ApplicationController
skip_before_action :authenticate_user!, only: [:index,:show, :search]
def index
if params[:query].present?
@response = DrugService.all_drugs(params[:query])
@drugs = []
@response.each { |drug| @drugs << { codeCIS: drug["codeCIS"], denomination: dr... |
class NavigationBar
include PageObject
include PageFactory
include DataMagic
include FooterPanel
include ErrorCatching
include WaitingMethods
link(:home_button, :id => 'home_link')
link(:transaction_detail, :id => 'transactionsLink0')
def go_to(page_name)
DataMagic.load 'navigation.yml'
@num... |
#
# Cookbook Name:: virtualmonkey
# Attribute:: default
#
# Copyright (C) 2013 RightScale, Inc.
#
# 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.apache.org/licenses/LICENSE-2... |
Pod::Spec.new do |s|
s.name = 'Mask'
s.version = '0.1.0'
s.summary = 'A short description of Mask.'
s.description = <<-DESC
TODO: Add long description of the pod here.
DESC
s.homepage = 'https://github.com/Huuush/Mask'
s.license = { :type => 'MIT', :file => 'LICEN... |
class Division < ActiveRecord::Base
paginates_per 50
has_many :votes
has_many :mps, through: :votes
has_one :division_info
has_many :whips
def find_mp(id)
find_by(deputy_id: id )
end
end
|
module AcquiaToolbelt
class CLI
class Environments < AcquiaToolbelt::Thor
# Public: List environments on a subscription.
#
# Output environment information.
#
# Returns enviroment data.
desc 'list', 'List all environment data.'
def list
if options[:subscription]
... |
# -*- encoding: utf-8 -*-
# stub: rib 1.6.1 ruby lib
Gem::Specification.new do |s|
s.name = "rib".freeze
s.version = "1.6.1"
s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib".freeze]
s.authors = ["Lin Jen-Shin (godfat)".fr... |
class RenameTables < ActiveRecord::Migration
def change
rename_table(:shoes, :brands)
rename_table(:shoes_stores, :brands_stores)
rename_column(:brands, :brand, :name)
end
end
|
FactoryGirl.define do
factory :locker do
name %w(S M L).sample + (1..1000).to_a.sample.to_s
size %w(Small Medium Large).sample
available true
end
end |
# frozen_string_literal: true
require 'rails_admin/config/fields/types/numeric'
module RailsAdmin
module Config
module Fields
module Types
class Integer < RailsAdmin::Config::Fields::Types::Numeric
# Register field type for the type loader
RailsAdmin::Config::Fields::Types.regi... |
require 'spec_helper'
require 'rails_helper'
describe Channel do
it "should make channel" do
c = Channel.new(:name => "Seinfeld", :image_url => "google.com", :network => "NBC", :api_id => 35)
expect(c.save).to be(true)
end
it "should fail channel" do
c = Channel.new(:image_url => "google.com")
... |
module Bridge
# Class representing bridge deal
class Deal
include Comparable
attr_reader :n, :e, :s, :w
# Returns cards of given direction
def [](direction)
must_be_direction!(direction)
send("#{direction.to_s.downcase}")
end
# Compares the deal with given deal
def <=>(oth... |
class Follower
attr_accessor :name, :age, :life_motto
@@all = []
def initialize(name, age, life_motto)
@name = name
@age = age
@life_motto = life_motto
@@all << self
end
def oaths
BloodOath.all.select do |oath|
oath.follower == self
end
end
def cults
oaths.map(&:cult)
... |
class PostsController < ApplicationController
before_action :require_user
def home
@posts = if params[:term]
Post.where('title LIKE ? or location LIKE ? or description LIKE ? or requirements LIKE ? or category LIKE ?', "%#{params[:term]}%", "%#{params[:term]}%", "%#{params[:term]}%", "%#{params[:term]}%... |
# Configure your routes here
# See: http://hanamirb.org/guides/routing/overview/
root to: 'home#index'
resources :books, only: %i[index new create]
|
include_recipe 'consul::install_binary'
include_recipe 'consul::ui'
include_recipe 'consul-template::default'
include_recipe 'haproxy::default'
file '/etc/haproxy/haproxy.cfg' do
action :delete
end
consul_service_def 'codequest' do
id 'codequest1'
port 5050
# address '192.168.1.3'
tags ['http']
# check(
... |
# This is a modified version of Daniel Berger's Getopt::ong class,
# licensed under Ruby's license.
require 'set'
class Thor
class Options
class Error < StandardError; end
LONG_RE = /^(--\w+[-\w+]*)$/
SHORT_RE = /^(-\w)$/
LONG_EQ_RE = /^(--\w+[-\w+]*)=(.*?)$|(-\w?)=(.*?)$/
SHORT_SQ_RE =... |
require "benchmark"
time = Benchmark.measure do
num = File.read("string_8.dat").delete("\n").each_char.map(&:to_i) # converts the number (loaded from a file) into an integer array
cur_first_i = 0 # index of the currently-checked first char, [0, 12] -> [1, 13] -> ...
largest_product = 0
while cur_first_i <= nu... |
#
# Cookbook Name:: stackdriver
# Recipe:: default
# License:: MIT License
#
# Copyright 2013, Stackdriver
#
# All rights reserved
#
include_recipe "stackdriver::repo"
# Install the stack driver agent
package "stackdriver-agent" do
action :install
end
# Create or update the stackdriver-agent config
template "/etc/... |
# -*- coding: utf-8 -*-
# topword.rb
# ver7
# 特別なことをやっていないように見えるのだけれど実はそうでもなくて、
# ここでは、Enumerableモジュールをハッシュクラスと配列クラスにインクルードしている。
# Enumerableモジュールとはクラスの亜種。
# オブジェクトを生成できないクラス。
module Enumerable
def take_by(nth)
sort_by { |elem| yield elem } .take(nth)
end
end
words = ARGF.read.downcase.scan(/\p{Word}+/)
dict... |
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'shelter index page', type: :feature do
it 'has links to edit and delete each shelter' do
visit '/shelters'
expect(page).to have_link('Edit')
expect(page).to have_link('Delete')
end
end
|
module Node
class Node < ApplicationRecord
has_one :led, dependent: :destroy
accepts_nested_attributes_for :led
has_one :button, dependent: :destroy
accepts_nested_attributes_for :button
has_one :neo_pixel_stick_eight, dependent: :destroy
accepts_nested_attributes_for :neo_pixel_stick_eight
def getC... |
class TunitsController < ApplicationController
before_action :set_tunit, only: [:show, :edit, :update, :destroy]
# GET /tunits
# GET /tunits.json
def index
@tunits = Tunit.all
end
# GET /tunits/1
# GET /tunits/1.json
def show
end
# GET /tunits/new
def new
@tunit = Tunit.new
end
# G... |
# frozen_string_literal: true
require_dependency "think_feel_do_dashboard/application_controller"
module ThinkFeelDoDashboard
# Allows for the creation, updating, and deletion of arms
class ArmsController < ApplicationController
rescue_from ActiveRecord::RecordNotFound, with: :arm_not_found
# GET /think_f... |
insert_into_file 'app/controllers/application_controller.rb', before: /^end/ do
<<-'RUBY'
rescue_from Exceptions::DefaultError do |e|
puts e.message if Rails.env.development?
flash[:error] = e.message
redirect_back(fallback_location: root_path)
end
RUBY
end |
require 'wsdl_mapper/dom/name'
require 'wsdl_mapper/naming/type_name'
require 'wsdl_mapper/naming/property_name'
require 'wsdl_mapper/naming/enumeration_value_name'
require 'wsdl_mapper/naming/namer_base'
module WsdlMapper
module Naming
# This is the default Namer implementation. It provides the de-facto stand... |
class Product < ApplicationRecord
has_many :cart_products
default_scope { where(active: true) }
end
|
class UpdateCollaboratorsTable < ActiveRecord::Migration
def change
rename_table :collaborators, :listusers
end
def change
rename_table :foodlists, :listeditems
end
end
|
#BooksContrololerにApplicationControllerを継承している
#ApplicationControllerという変数をBooksControllerに渡し定義している
class BooksController < ApplicationController
#indexアクションを実行するための処理
def index
#全ての家計簿データを@booksというインスタンス変数に値を格納している
@books = Book.all
end
#showアクションを実行するための処理
def show
#コントロ... |
#!/usr/bin/env ruby
#
# a simple database backup-script
require 'optparse'
require 'ostruct'
require 'date'
class BackupJob
VERSION = 0.1
# expects pgpass set for effektive userid
#
def initialize(argv)
op = option_parser
op.parse!(argv)
check_options
end
def run
process
end
p... |
require 'rails_helper'
RSpec.describe BattleService do
let(:combat) { create :combat }
let(:player1) { create :player }
let(:player2) { create :player }
describe "validation" do
it "no errors, 'cause everything's correct" do
described_class.new(combat, {"player1_id" => player1.id.to_s,
... |
# frozen_string_literal: true
module Dynflow
module Stateful
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def states
raise NotImplementedError
end
def state_transitions
raise NotImplementedError
end
end
def states
s... |
class AddEvents < ActiveRecord::Migration
def change
create_table :events do |t|
t.string :name
t.date :date
t.integer :num_user
t.float :reg_price
t.float :disc_price
t.integer :min_required
t.string :image_url
t.string :location
t.timestamps
end
... |
class AddPromotionPdfToGlobalSetting < ActiveRecord::Migration
def self.up
add_attachment :global_settings, :promotions_pdf
end
def self.down
remove_attachment :global_settings, :promotions_pdf
end
end
|
require 'spec_helper'
describe Admin::IssueDetail do
let(:markdown_editor_functions) { double(Admin::MarkdownEditorFunctions, issue_content_status: 'Done', issue_content_link: '/admin/volumes/test') }
let(:issue) { double(Issue, id: 1, title: 'title', published?: true, is_pdf?: true, essays: [1,2,3])}
subject {... |
class OrderSerializer < ActiveModel::Serializer
attributes :id, :status, :user, :credentials, :address
def user
{
id: object.user.id,
mail: object.user.email
}
end
def credentials
{
id: object.user.credential.id,
title: object.user.credential.title,
name: object.user... |
#
# Author:: Edward Nunez(edward.nunez@cyberark.com)
# Author:: CyberArk Business Development (<business_development@cyberark.com>)
# Cookbook:: cyberark
# Resource:: cyberark_credential
#
# Copyright:: 2017, CyberArk Software
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this fi... |
require 'byebug'
module SlidingPiece
def moves
result = []
directions = move_dirs
directions.each do |dir|
result += grow_unblocked_moves_in_dir(dir[0], dir[1])
end
result
end
private
def move_dirs
end
def horizontal_dirs
[
[ 1, 0],
[-1, 0],
[ 0, 1],
... |
class AddTownToSlope < ActiveRecord::Migration
def change
add_column :slopes, :town, :string
end
end
|
require 'rails_helper'
RSpec.describe AttachmentsController, type: :controller do
let(:user) { create(:user) }
describe "DELETE#destroy" do
let(:answer) { create(:answer_with_attached_file) }
let(:question) { create(:question_with_attached_file) }
context 'An author of answer deletes attached file' ... |
class Station
include InstanceCounter
attr_reader :name
attr_accessor :trains
REGEXP = /[a-z]/i
@@list = []
def initialize(name)
@name = name
@trains = []
validate!
@@list << self
register_instance
end
def self.all
@@list
end
def valid?
validate!
true
rescue... |
class AdminMailer < ActionMailer::Base
default from: 'Happy Dining <no-reply@happydining.fr>'
def new_reservation reservation
@reservation = reservation
@time = reservation.time.strftime("%d/%m/%Y, at %H:%M")
@user = reservation.user
@restaurant = reservation.restaurant
@user_contribution = @reser... |
class Post < ActiveRecord::Base
belongs_to :user
has_many :comments, :dependent => :destroy
#validations
validates :title, presence: true, uniqueness: true
validates :body, length: {maximum: 150}, presence: true
end
|
require 'pry'
require 'io/wait'
#A one player blackjack game.
#Follows rules at:
#http://www.cs.bu.edu/~hwxi/academic/courses/CS320/Spring02/assignments/06/blackjack.html
#The game logic is contained in the do_action method
#A card is represented as a hash of form #
#{:rank => string, :suit => "string"}
#The game ... |
require '~/ruby_libs/solea/solea'
class HTMLElement
attr_reader :tagname, :attributes, :children
attr_accessor :content
def initialize tagname, content = nil, attrs = {}, &block
@tagname = tagname
@attributes = attrs
@content = [content].compact
block.call(@content) if block_given?
end... |
module LiquidTags
class NeiUsageSummary < Liquid::Tag
include ActionView::Helpers::NumberHelper
include Memoizer # rubocop:disable Wego/ImplicitMemoizer
attr_reader :audit_report,
:audit_report_calculator
ENERGY_FIELDS = [
:annual_energy_usage_existing,
:annual_energy_sav... |
class CreatePayments < ActiveRecord::Migration
def change
create_table :payments do |t|
t.integer :order_id, null: false
t.decimal :amount, null: false, precision: 9, scale: 2
t.string :state, null: false, limit: 20
t.string :external_id, limit: 100
t.decimal :external_fee, precision... |
class Importers::DishForm < Importers::BaseForm
attr_accessor(
:id,
:name,
:description,
:menus_appeared,
:times_appeared,
:first_appeared,
:last_appeared,
:lowest_price,
:highest_price,
)
validates :id, :name, presence: true
validates :id, numericality: true
end
|
class AddSlugToDiscountType < ActiveRecord::Migration[5.1]
def change
add_column :discount_types, :slug, :string
end
end
|
module ApiHelper
def auth_header(token)
ActionController::HttpAuthentication::Token.encode_credentials(token)
end
def api_user(user)
allow(user).to receive(:to_sgid).and_return('test.user')
session = Givdo::TokenAuth::Session.new(user, false)
request.env['HTTP_AUTHORIZATION'] = auth_header(sessio... |
# license
require 'json'
module Darknet
class Results < Array
def self.parse(rows)
# rows of data like:
# RV: 94% (left_x: 925 top_y: 587 width: 34 height: 21)
# RV: 100% (left_x: 1148 top_y: 600 width: 37 height: 28)
rows = rows.split("\n").collect do |line|
... |
class PayrollsController < ApplicationController
before_filter :payroll_owner
layout 'application-admin'
def show
@payroll = Payroll.find(params[:id])
end
def create
current_user.payrolls.find_by_draft(true).try(:destroy)
@payroll = current_user.payrolls.build(:start_date => Time.zon... |
class AddAgencyIdToAgencyArtist < ActiveRecord::Migration[6.0]
def change
add_column :agency_artists, :agency_id, :integer
end
end
|
# Asks user to type required information in
# Defining a method because its prior to caesar_cipher
def main
puts "Please, enter a string which you want to cipher!"
user_string = gets.chomp
puts "Please, enter positive number"
user_number = gets.chomp.to_i
caesar_cipher(user_string, user_number)
end
... |
require 'CSV'
require 'bigdecimal'
require_relative 'sales_engine'
class SalesAnalyst
attr_reader :engine
def initialize(engine)
@engine = engine
end
def average(data)
data.sum / data.size.to_f
end
def standard_deviation(sample_size)
Math.sqrt(sample_size.sum do |sample|
(sample - aver... |
require "spec_helper"
describe "#double" do
let(:fake_object) { double("fake_object", fake_function: "fake function") }
it "is mock object with the RSpec::Mocks::Double class " do
expect(fake_object.class).to eq(RSpec::Mocks::Double)
end
it "can have stubbed functions" do
expect(fake_object.fake_func... |
# encoding: utf-8
$LOAD_PATH.unshift File.expand_path("../lib", __dir__)
require "rbmisc"
require "minitest/autorun"
require "minitest/spec"
# require 'simplecov'
# SimpleCov.start
require 'yaml'
require 'fileutils'
# Helper methods and utilities for testing.
# Helper method to allow temporary redirection of $std... |
class GameSession < ActiveRecord::Base
has_many :games
has_many :decks
has_many :cards, through: :decks
belongs_to :user
after_create :create_decks
NUMBER_OF_DECKS = 6
def number_of_decks
NUMBER_OF_DECKS
end
def create_decks
NUMBER_OF_DECKS.times do
Deck.create!(game_session_id: id)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.