text stringlengths 10 2.61M |
|---|
class StatusMailer < ApplicationMailer
default from: 'notifications@xtremefarmbot.com'
def status_email(action)
@action = action
mail(to: 'fages.fages@gmail.com', subject: 'Farm Status Report')
end
end
|
module Fog
module Compute
class Brkt
class Real
def create_server(image_id, machine_type_id, name, workload_id, options={})
body = Fog::StringifyKeys.stringify(options).merge({
"image_definition" => image_id,
"machine_type" => machine_type_id,
"name"... |
class Dashboard::IssuesController < DashboardController
def index
@title = "Issues"
@issues = Issue.page(params[:page]).order("homepage DESC")
end
def show
redirect_to :action => :edit
end
def new
@issue = Issue.new
end
def create
@issue = current_user.created_issues.build(params... |
json.extract! @comment, :id, :comment_id, :created_at, :updated_at
json.body @comment.enhanced_body
json.is_pose @comment.pose?
json.votes_count @comment.votes.count
json.image_url @comment.has_image? ? paperclip_url(@comment.image(:large)) : nil
if 'Journal' == @comment.commentable_type
json.comments_url journ... |
# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.
class ApplicationController < ActionController::Base
helper :all # include all helpers, all the time
# See ActionController::RequestForgeryProtection for details
... |
require 'spec_helper'
require 'transcoder'
describe FlowService do
subject { FlowService.new(identifier: 'unique_id',
filename: 'filename.wav',
title: 'yaas audio',
contributors: 'i made this') }
describe 'clean' do
it 'is suc... |
class ZeroCourses::Home < Page
attr_accessor :prerequis, :objectif
def initialize(home_hash)
page_ash = {}
home_hash.each do |attribute, value|
page_ash[attribute] = value if attribute != :prerequis && attribute != :objectif
end
super(home_hash)
@prerequis = h... |
class TestsController < ApplicationController
rescue_from ActiveRecord::RecordNotFound, with: :rescue_with_test_not_found
def index
@tests = Test.all
end
def start
@test = Test.find(params[:id])
current_user.tests.push(@test)
redirect_to current_user.user_passed_test(@test)
end
private
... |
class Api::V1::CommentsController < ApplicationController
def index
project = Project.find_by(id: params[:project_id])
comments = project.comments
render json: comments, only: [:content, :updated_at, :created_at]
end
def create
user = current_user
project = Project.find_by(id: params[:projec... |
require 'spec_helper'
describe ImportPage::Importers::PageImporter do
subject{ described_class.new(section.id, genre, user.id, html_file) }
let!(:section) { create(:section) }
let!(:genre) { create(:genre) }
let!(:user) { create(:user) }
let(:store_dir) { Pathname.new(ImportPage::UploadFile.store_path(sec... |
class AddAttributesToRecipes < ActiveRecord::Migration[6.0]
def change
add_column :recipes, :total_cost, :float
add_column :recipes, :cost_per_serving, :float
end
end
|
class AddCatcphraseColumnToCharacterTable < ActiveRecord::Migration[6.0]
def change
add_column :characters, :catchphrase, :string
end
end
|
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
describe Blueprints::Buildable do
it "should inspect buildable nicely" do
namespace_blueprint.attributes(:attr => 'value').depends_on(:dependency)
namespace_blueprint.inspect.should == %q(<#Blueprints::Blueprint name: "namespace.blueprint", at... |
# 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 rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Ch... |
# typed: true
# frozen_string_literal: true
require 'test_helper'
module Ffprober
module Ffmpeg
class VersionValidatorTest < Minitest::Test
def test_valid
version = Ffprober::Ffmpeg::Version.new
Ffprober::Ffmpeg::VersionValidator.new(version)
end
end
end
end
|
Rails.application.routes.draw do
get 'products/index'
post "products" => 'products#create'
get 'products/new'
root 'products#index'
resources :products
end
|
class Gmp < BuildDependency
desc "GNU multiple precision arithmetic library"
homepage "https://gmplib.org/"
url "https://gmplib.org/download/gmp/gmp-${version}.tar.xz"
release version: '6.1.2', crystax_version: 3
def build_for_platform(platform, release, options, _host_deps_dirs, _target_dep_dirs)
inst... |
Rollbar.configure do |config|
config.enabled = ENV.has_key?('ROLLBAR_ACCESS_TOKEN')
config.access_token = ENV["ROLLBAR_ACCESS_TOKEN"]
config.use_sucker_punch
end
|
# @param {String} haystack
# @param {String} needle
# @return {Integer}
require "pry"
def str_str(haystack, needle)
return 0 if needle.length == 0
index,offset = 0,0
flag = false
for index in (0..haystack.length-needle.length+1)
flag = true
for offset in (0...needle.length)
if needle[offset] ... |
class CreateTaskChoices < ActiveRecord::Migration
def self.up
create_table :task_choices do |t|
t.string :content
end
end
def self.down
drop_table :task_choices
end
end
|
require_relative 'piece'
class SteppingPiece < Piece
def initialize(board, location, color, step)
super(board, location, color)
@step = step
end
def valid_move?(move)
return false unless super(move)
dx = move[0] - @location[0]
dy = move[1] - @location[1]
@step.include?([dx, dy])
end
e... |
require "application_system_test_case"
class ChallengesTest < ApplicationSystemTestCase
before do
@service = login_service
@tournament = create(:started_tournament)
@rating_period = @tournament.current_rating_period
@player1 = create(:player, :user => @service.user, :tournament => @tournament)
@p... |
class Dashboard::OjsImportsController < DashboardController
def index
@title = "OJS Imports"
@ojs_imports = OjsImport.includes(:issue).page(params[:page]).order("updated_at DESC")
end
def new
@ojs_import = OjsImport.new
end
def confirm
@ojs_import = OjsImport.new(params[:ojs_import])
if... |
class RoomTypesController < ApplicationController
def show
@room_type = RoomType.find_by slug: params[:id]
if @room_type
@rooms = Room.available.by_room_type_id @room_type.id
else
flash[:warning] = t ".not_found"
redirect_to root_path
end
end
end
|
class AmazonAccount < Account
has_many :product_snapshots
has_many :recommendation_snapshots
has_many :recommendations
has_many :products
end
|
require "rails_helper"
RSpec.describe MatchingService, type: :service do
describe "#match_all_customer_by_pet" do
let(:pet) { build(:pet) }
let(:matching) { MatchingService.new.match_all_customer_by_pet(pet) }
it "returns no customers" do
expect(matching.size).to eq(0)
end
it "returns a c... |
class AddStorageToUsers < ActiveRecord::Migration[5.2]
def change
add_column :users, :storage, :json
end
end
|
class Property
def initialize
@available = true
end
def available?
@available
end
def bought
@available = false
end
end |
class QuestionPlay < ActiveRecord::Base
belongs_to :user
belongs_to :question
belongs_to :answer
belongs_to :level_play
# validates_associated :user, :question, :answer, :level_play
# validates :score, numericality: { only_integer: true }
# validates :user_id, :question_id, :answer_id, :level_play_id, ... |
# == Schema Information
#
# Table name: posts
#
# id :integer not null, primary key
# title :string
# body :text
# created_at :datetime not null
# updated_at :datetime not null
#
class Post < ActiveRecord::Base
has_many :comments, as: :commentable
validates :title,... |
module Datomic
def self.download_url(license_type, version)
if license_type == "pro"
"https://my.datomic.com/repo/com/datomic/datomic-pro/#{version}/datomic-pro-#{version}.zip"
else
"https://my.datomic.com/downloads/free/#{version}"
end
end
def self.download_auth(license_email, license_do... |
class Team < ApplicationRecord
belongs_to :sport
has_many :user_teams, dependent: :destroy
validates :name, presence: true, uniqueness: true
end
|
#encoding: utf-8
class MaterialOrder < ActiveRecord::Base
has_many :mat_order_items
# has_many :mat_out_orders
# has_many :mat_in_orders
has_many :m_order_types
has_many :materials, :through => :mat_order_items
belongs_to :supplier
belongs_to :store
scope :is_headoffice_not_canceled, where(:supplier_id =>... |
#encoding: utf-8
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# name :string(255)
# email :string(255)
# created_at :datetime not null
# updated_at :datetime not null
# password_digest :string(255)
# birth... |
Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
namespace :api do
namespace :v1 do
resources :items do
match 'find_all', via: %i[get], as: :find_all, on: :collection
match 'find', via: %i[get], as: :find, ... |
module ApplicationHelper
# Overwrite `current_user` helper of devise
def current_user
super || guest_user
end
def guest_user
User.new name: "Guest User", email: "guest@local.com"
end
# View helper: Return title for a page
def page_title title = ""
title.empty? ? "Dissect" : title
end
# ... |
class AddKringles < ActiveRecord::Migration
def change
create_table :kringles do |t|
t.belongs_to :kringlehead
end
end
end
|
class MakeUserAssociationPolymorphic < ActiveRecord::Migration
def change
add_column :user_associations, :group_id, :integer
add_column :user_associations, :group_type, :string
end
end
|
class District < ApplicationRecord
has_many :users
has_one :representative_seat
belongs_to :state
end
|
#
# Be sure to run `pod lib lint RunOnce.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'RunOnce'
s... |
require 'rails_helper'
RSpec.describe "When I visit the studio index page" do
before(:each) do
@paramount = Studio.create(name: "Paramount", location: "California" )
@a24 = Studio.create(name: "A24", location: "New York" )
@interstellar = @paramount.movies.create(title: "Interstellar", creation_year: 20... |
class AromasController < ApplicationController
before_action :aroma_params, only: [:create, :update]
def index
@aromas = Aroma.all
end
def new
@aroma = Aroma.new
end
def create
Aroma.create(aroma_params)
redirect_to root_path
end
def edit
@aroma = Aroma.find(params[:id])
end
... |
class CreateStores < ActiveRecord::Migration[6.0]
def change
create_table :stores do |t|
t.string :management_type, {null: false, limit: 30}
t.references :houses
t.integer :electricity, {null: true, limit: 1}
t.integer :water, {null: true, limit: 1}
t.timestamps
end
end
end
|
module ServerThinkingSphinx
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
include PathConfig
def thinking_sphinx_service_state
pid_file_path = thinking_sphinx_service_pid_file
ManagementUtil.check_process_by_pid_file(pid_file_path)
end
def... |
class AddColumnToConversations < ActiveRecord::Migration[5.0]
def change
add_column :conversations, :speaker, :string
end
end
|
### Global Variables
$foods = Array.new
$prices = Array.new
$name = Array.new
$history = Array.new
### Classes
class Map
attr_reader :size, :cell
def initialize(size)
@size = size
@cell = Array.new
for i in (0...size)
temp = Array.new
for j in (0...size... |
class AssetPolicy < ApplicationPolicy
class Scope < Scope
def resolve
user.nil? || user.is_computacenter? ? scope.none : scope.all
end
end
def show?
user.present? && !user.is_computacenter?
end
end
|
Protocol::Engine.routes.draw do
resources :assessments, path: I18n.t('routes.protocol.assessments')
end
|
class ChangeTableIdToPinId < ActiveRecord::Migration
def change
rename_column :high_scores, :table_id, :pin_id
end
end
|
#! /usr/bin/env ruby
#
# metrics-couchbase
#
# DESCRIPTION:
# This plugin collect metrics from couchbase REST API.
#
# OUTPUT:
# plain text
#
# PLATFORMS:
# Linux
#
# DEPENDENCIES:
# gem: sensu-plugin
# gem: rest-client
# Gem: json
#
# USAGE:
#
# NOTES:
# This plugin is tested against couchbase 2.5.x
#
... |
class Doc < OpenStruct
include ActiveModel::Validations
include ActiveModel::Conversion
extend ActiveModel::Naming
def initialize(*args)
super
end
def persisted?
false
end
end |
# all grape extend it
class BaseGrape < Grape::API
include Grape::Rails::Cache
content_type :json, 'application/json'
default_format :json
helpers ApplicationHelper, ErrorHelper, DataBuildHelper, CacheHelper
# 401
rescue_from(SignError) { |e| auth_error!(e) }
rescue_from(Svc::JwtSignature::SignError) {... |
# frozen_string_literal: true
namespace :feed do
desc 'Update all feeds'
task update: :environment do
require 'recurring/update_feed'
UpdateFeed.new.perform
end
desc 'Apply filters to existing newsitems'
task filter: :environment do
require 'shreds/feed/filters'
Newsitem.find_each do |n|
... |
class ApplicationController < ActionController::Base
def redirect_to_login_page_if_not_logged_in
if !session[:user_id]
redirect_to login_path
end
end
# before_action :require_login
# skip_before_action :require_login, only: [:index]
private
def require_login
... |
class Participants
attr_accessor :name, :role, :hand, :account, :game_played
def self.all
@@participants
end
def initialize(role, name = nil)
@@participants ||= []
@name = name
@role = role
@hand = Hand.new
@account = Account.new
@game_played = 0
@@participants << self
v... |
#!/usr/bin/env ruby
# encoding: utf-8
class HatenaStar
# 2)
def reviews_of(article)
sleep 1
lank = rand(10)
star = '☆'
"[#{article}]: #{star * lank}"
end
end
class HatenaStar
# 1)
alias :default_reviews_of :reviews_of
# 3)
def reviews_of(article)
start = Time.now
# 5)
result... |
require 'telegram/bot'
require_relative '../lib/message_handler'
require_relative 'guarani_client'
require 'telegram/bot'
require_relative '../app/helpers/emoji'
require 'json'
require_relative '../app/helpers/astapor_api_error'
DEFAULT_MESSAGE = "Perdon! No se como ayudarte con eso #{Emoji.code(:speak_no_evil)}" \
... |
class RunInstance
def initialize(options)
@options = options
@state = RunInstanceState.new(id)
end
def id
@id ||= Time.now.to_i
end
def each_iteration
raise NotImplementedException.new
end
def on_start
raise NotImplementedException.new
end
def on_complete
raise NotImpleme... |
When /^I login$/ do
fill_in('username', :with => 'user')
fill_in('password', :with => 'user')
click_button('Log in')
end
When /^I login as "([^\"]*)"$/ do |username|
fill_in('username', :with => username)
fill_in('password', :with => username)
click_button('Log in')
end
When /^I login as "([... |
require 'rails_helper'
RSpec.describe 'Listモデルのテスト', type: :model do
describe 'バリデーションのテスト' do
subject { list.valid? }
#vaild?がvalidationのチェックの話をしている
let(:list) { create(:list) }
context 'titleカラム' do
it '空欄でないこと' do
list.title = ''
#validationの設定の結果が返ってきたらfalseとなるため下記が通る
... |
require "rails_helper"
describe "Api::V1::Adresses", type: :request do
context "GET adresses" do
let(:url) { "/api/v1/adresses" }
let!(:professional) { create(:professional) }
let(:adresses) { create(:address, professional_id: professional.id) }
it "returns all Adresses" do
get url, params: ad... |
require_relative '../acceptance_helper'
feature 'searching with sphinx' do
given!(:user) { create(:user) }
given!(:question) { create(:question, title: 'question', user: user) }
given!(:answer) { create(:answer, body: 'answer', question: question, user: user) }
given!(:comment) { create(:comment, body: 'commen... |
class AddPaperClipToMediaMedia < ActiveRecord::Migration
def change
add_attachment :media_media, :file
end
end
|
class Admin::GroupsController < AdminController
# GET /groups
def index
@groups = Group.all
end
# GET /groups/1
def show
@group = Group.find(params[:id])
end
# GET /groups/new
def new
@group = Group.new
end
# GET /groups/1/edit
def edit
@group = Group.find(params[:id])
end
... |
# frozen_string_literal: true
## --- BEGIN LICENSE BLOCK ---
# Copyright (c) 2016-present WeWantToKnow AS
#
# 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 wit... |
# rubocop:disable Metrics/BlockLength
Given(/^a taxon in the middle of the taxonomy$/) do
@taxon = {
content_id: 'taxon-uuid',
base_path: '/education/further-education',
title: 'Further education',
description: 'Further education content',
document_type: 'taxon',
links: {
parent_taxons: ... |
#!/usr/bin/env ruby
# The MIT License (MIT)
# Copyright (c) 2014 Claudius Coenen
#
# 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... |
class Doctor < ActiveRecord::Base
has_many :facilities through: :facility_doctors
has_many :facility_doctors
end
|
require "test/unit"
require File.dirname(__FILE__) + "/../lib/assertion_fu"
class AssertionFuTest < Test::Unit::TestCase #:nodoc:
include AssertionFu
def test_file_exists
assert_file_exists(__FILE__)
assert_file_doesnt_exist(__FILE__ + "dfadsfa")
end
def test_file_includes
assert_file_include... |
# frozen_string_literal: true
module KeycloakAdapter
class AuthorizationError < StandardError; end
class MissingTokenError < AuthorizationError; end
end
Dir[Rails.root.join('lib', 'keycloak_adapter', '*.rb')].each { |file| require file }
|
class CmspagesController < ApplicationController
before_filter :authenticate_user!
layout 'admin'
def index
@cmspages = Cmspage.find(:all)
respond_to do |format|
format.html # index.html.erb
format.json { render json: @cmspages }
end
end
def show
@cmspage = Cmspage.find(param... |
class CreateComments < ActiveRecord::Migration[5.0]
def change
create_table :comments do |t|
t.string :commenter
t.text :body
t.references :article, foreign_key: true
#The t.references line creates an integer column called article_id, an index for it,
#and a foreign key constraint th... |
class FriendshipRelationType < ActiveRecord::Base
belongs_to :friendship
belongs_to :relation, :class_name => "RelationType"
end |
require_relative 'uuid_callbacks'
module Diagroo
module UUID
# rubocop:disable Metrics/LineLength
REGEX_PATTERN = /[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89aAbB][a-f0-9]{3}-[a-f0-9]{12}/
def self.extend_object(obj_class)
obj_class.instance_eval do
attribute :uuid
index :uuid
... |
class Contracts::EditSerializer < ApplicationSerializer
object_as :contract
identifier :slug
attributes(
:id,
:slug,
:name,
:number,
:notes,
:begins_at,
:ends_at,
:vendor_id,
:category_id,
)
belongs_to :vendor, serializer: Vendors::OptionsSerializer
belongs_to :categor... |
module Auth
class Panel::AuthorizedTokensController < Panel::BaseController
before_action :set_authorized_token, only: [:edit, :update, :destroy]
def index
q_params = {}
q_params.merge! params.permit(:token, :oauth_user_id, :user_id, :account_id)
@authorized_tokens = AuthorizedToken.default... |
# encoding: utf-8
module Werdau
class Redirect < ActiveRecord::Base
self.abstract_class = true
SYNCHRONIZED_CATEGORIES = {
'DVD плееры' => 'DVD-плееры', 'Телевизоры LCD и плазменные панели' => 'LCD-телевизоры',
'Аксессуары' => 'Подставки и крепления', 'ОЧКИ 3D' => '3D очки',
'Плееры' => ... |
$:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "task_master/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "task_master"
s.version = TaskMaster::VERSION
s.authors = ["Sean Devine"]
s.email = ["barelykn... |
class AccountBalances
def initialize(user:, account:, month:)
raise unless account.user == user
@account = account
@month = month
end
attr_reader :account, :month
def balances
account.balances
.where(currency: account.currency)
.where("DATE_TRUNC('month', balances.date) = ?", parse... |
require './lib/tilt'
Gem::Specification.new do |s|
s.name = 'tilt'
s.version = Tilt::VERSION
s.description = "Generic interface to multiple Ruby template engines"
s.summary = s.description
s.license = "MIT"
s.authors = ["Ryan Tomayko", "Magnus Holm", "Jeremy Evans"]
s.email = "r@tomayko.com"
... |
require 'spec_helper'
module Naf
describe LoggerLevel do
# Mass-assignment
[:level].each do |a|
it { should allow_mass_assignment_of(a) }
end
[:id,
:created_at,
:updated_at].each do |a|
it { should_not allow_mass_assignment_of(a) }
end
#---------------------
# *** ... |
class DropBuildGrowthFromAttendeeCharacter < ActiveRecord::Migration[6.0]
def change
remove_column :attendee_characters, :build_growth, :integer
end
end
|
class Api::V1::ReviewsController < ApiController
before_action :authenticate_user!, except: [:show, :index]
def index
render json: Review.all
end
def show
cape = Cape.find(params["id"])
reviews = cape.reviews
render json: reviews
end
def create
review = Review.new(review_params)
c... |
class PromotionCode
include Mongoid::Document
include Mongoid::Timestamps
include Mongoid::Attributes::Dynamic
include FullErrorMessages
field :code
field :used_by
embedded_in :promotion
end
|
Vagrant.configure("2") do |config|
config.vm.box = "ubuntu_aws"
config.vm.box_url = "https://github.com/mitchellh/vagrant-aws/raw/master/dummy.box"
config.vm.provider "virtualbox" do |v|
v.memory = 1024
end
config.vm.define :web do |web_config|
web_config.vm.network "private_network... |
require_relative 'computer'
require_relative 'user'
require_relative 'victory'
class Game
POSSIBLE_OUTCOMES = [:win, :draw, :lose]
CHOICES = [:rock, :paper, :scissors]
RESULTS = { :rock => {:rock => :draw, :paper => :lose, :scissors => :win},
:paper => {:rock => :win, :paper => :draw, :sc... |
class Pledge < ApplicationRecord
belongs_to :user
belongs_to :project
# accepts_nested_attributes_for :projects
# def user_attributes=(user_attributes)
# self.pledges = Project.find_or_create_by(name: pledge_attributes[:username], email: user_attributes[:email]) unless user_attributes[:username].blank?
#... |
class String
def color_black
"\033[30m#{self}\033[0m"
end
def color_red
"\033[31m#{self}\033[0m"
end
def color_green
"\033[32m#{self}\033[0m"
end
def color_brown
"\033[33m#{self}\033[0m"
end
def color_blue
"\033[34m#{self}\033[0m"
end
def color_magenta
"\033[35m#{self... |
# frozen_string_literal: true
class QuizTrial::ResultSerializer < ApplicationSerializer
property(:answered_questions_count)
property(:correct_answers_count)
delegate :answered_questions_count, :correct_answers_count, to: :model
end
|
class RemovebankNameFromstockHolds < ActiveRecord::Migration[5.0]
def change
remove_column :stock_holds, :bank_name, :string
remove_column :stock_holds, :nisa_year, :string
end
end
|
# frozen_string_literal: true
Hanami.application.register_provider :assets do
start do
require 'framework/web/assets'
assets = Framework::Web::Assets.new(
root: Hanami.application.root,
precompiled: Hanami.env == :production || target['settings'].precompiled_assets,
server_url: Hanami.appl... |
class AddTechToCodeName < ActiveRecord::Migration
def change
add_column :code_names, :tech, :integer, default: 0
end
end
|
module HomeWatcher::Server::Writer
def recieve_and_write
message = (@socket.gets || '').chomp
write(message)
@logger.info "inputed: #{message}"
end
private
def write(message)
File.write('/tmp/home_watcher', message)
@socket.write '200'
end
end
|
# frozen_string_literal: true
module Kafka
module Protocol
class AlterConfigsResponse
class ResourceDescription
attr_reader :name, :type, :error_code, :error_message
def initialize(name:, type:, error_code:, error_message:)
@name = name
@type = type
@error_cod... |
class Circuit
BOUNDARY = 65_536
def initialize(signals = {})
@signals = signals
@wires = {}
end
def assemble!(instructions)
instructions.each do |step|
source, wire = step.split(" -> ")
@wires[wire] = source.split
end
end
def reset!(signals = {})
@signals = signals
end
... |
class Gear
attr_reader :chainring, :cog, :wheel
def initialize(args)
@chainring = args[:chainring]
@cog = args[:cog]
@wheel = args[:wheel]
end
def ratio
chainring/ cog.to_f
end
def gear_inches
#tire goes around rim twice for diameter
ratio * diameter
end
def diameter
wheel.diameter
end
... |
require 'rails_helper'
RSpec.describe "admin/districts/index", type: :view do
let(:city) { FactoryGirl.create :city }
before(:each) do
assign(:districts, [
District.create!(name: FFaker::Name.name, city: city),
District.create!(name: FFaker::Name.name, city: city)
])
end
it "renders a list... |
module Api
class LotteriesController < ApiController
def create
amount = params[:amount].to_i
total = User.where(status: 'active').count
amount > total ? amount = total : amount
users = User.where(status: 'active').limit(amount).order("RANDOM()")
if users.length > 0
users.e... |
require 'spec_helper'
describe Disqussion::Applications do
Disqussion::Configuration::VALID_FORMATS.each do |format|
context ".new(:format => '#{format}')" do
before do
@client = Disqussion::Client.applications
end
context "listUsage" do
before do
stub_get("applic... |
#Week 2
friends = ["Danny", "Jack", "Jamie", "Ben"]
def number_of_friends(array)
result = array.length
p "You have #{result} friends."
end
number_of_friends(friends)
# "friends" is an array of names. The function "number_of_friends" uses the length method on the array to find the number elements within the arra... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.