text stringlengths 10 2.61M |
|---|
# -*- coding: utf-8 -*-
# frozen_string_literal: true
class RandomService
def pseudo_random(seed, index = 11, mod = 11117)
index.times.reduce(seed) { |x, _i| x * x % mod }
end
def date_seed(date, year_rank = 10000, month_rank = 100, day_rank = 1)
date.year * year_rank + date.month * month_rank + date.day * day... |
# require 'test_helper'
# class CustomerTest < ActiveSupport::TestCase
#
# setup do
# @new_customer = Customer.new
# end
#
# test 'Customer class exists' do
# assert class_exists?(Customer)
# end
#
# test 'Type should equal to Customer' do
# assert @new_customer.type == 'Customer'
# end
#
# te... |
module Exchanges
module Gdax
extend ExchangeMethods
extend self
def configured?
!!(settings["api_key"] && settings["api_secret"] && settings["api_passphrase"])
end
def client
raise "GDAX not configured in config/exchanges.yml" unless configured?
require 'coinbase/exchange'
... |
require "spec_helper"
describe BlogController, :type => :routing do
describe "routing" do
it { should route(:get, '/blog/index').to(controller: 'blog', action: 'index') }
end
end
|
class ApplicationController < ActionController::Base
protect_from_forgery with: :null_session
before_action :configure_permitted_parameters
def resource_name
:user
end
def resource
@resource ||= User.new
end
def resource_class
User
end
def configure_permitted_parameters
devise_paramet... |
class CategoriesController < ApplicationController
def index
@categories = DocCategory.all
render json: @categories
end
end
|
require 'crack'
module Plugins
class Wolfram
include Cinch::Plugin
include Cinch::Helpers
include ActionView::Helpers::DateHelper
enable_acl
self.plugin_name = 'Wolfram Alpha plugin'
self.help = 'WIP'
match /wolfram (.+)/, method: :calculate
match /wolframalpha (.+)/, method: :calc... |
class RegistrationsController < Devise::RegistrationsController
def new
@forecast = current_forecast
@plan_id = params[:plan_id]
@advice_hours = opening_advice_hours
super
end
def create
@user = User.new sign_up_params
#@user.plan_id = params[:plan_id]
if @user.save_with_payment
... |
require 'rubygems'
Gem::Specification.new do |gem|
gem.name = 'adsb'
gem.version = '0.2'
gem.author = 'Fred Noonan'
gem.email = 'frednoonan@hushmail.com'
gem.platform = Gem::Platform::RUBY
gem.summary = 'A library to deal with ADS-B (secondary flight radar) data'
gem.descripti... |
require 'rails_helper'
describe OrderPurchase do
before do
@order_purchase = FactoryBot.build(:order_purchase)
end
describe '配送先・取引情報情報の保存' do
it 'すべての値が正しく入力されていれば保存できること' do
expect(@order_purchase).to be_valid
end
end
context '配送先・取引情報情報の保存がうまくいかないとき' do
it 'tokenが空だと保存できないこと... |
#!/usr/bin/ruby
require 'set'
# Identifier
class Ident
attr_reader :name
def initialize(name); @name = name; end
def to_s; @name; end
end
# Function application
class Apply
attr_reader :fn, :arg
def initialize(fn, arg)
@fn = fn
@arg = arg
end
def to_s
"(#{@fn} #{@arg})"
end
end
# Lambda ... |
class Analytics::Stats
include Redis::Objects
sorted_set :query_hits, :global => true
def all
query_hits.revrange(0, -1, with_scores: true)
end
def update_stats!
until (user_id = Analytics::Query.next) == nil
update_stats_from_user user_id
end
update_query_stats
'OK'
end
d... |
require 'sinatra'
require 'json'
require 'git'
require 'bunto'
post '/' do
dir = './tmp/bunto'
name = "BuntoBot"
email = ENV['EMAIL'] || ''
username = ENV['GH_USER'] || ''
password = ENV['GH_PASS'] || ''
FileUtils.rm_rf dir
push = JSON.parse(params[:payload])
if push["commits"].first["author"]["... |
# frozen_string_literal: true
RSpec.describe User, type: :model do
it { should have_many(:submitted_talk_summaries) }
context 'queries' do
it 'talk_summaries' do
alice = create(:user)
talk = create(:talk)
talk_summary = create(
:talk_summary, :just_pass_validation,
talk: talk... |
class Listing < ApplicationRecord
belongs_to :host, class_name: 'User'
validates :address, presence: true
# Geocoder gem: https://github.com/alexreisner/geocoder
geocoded_by :full_address, latitude: :lat, longitude: :long
after_validation :geocode
def country
ISO3166::Country.new(country_code)
end
... |
module SchedulerService
class BuildRunner
def initialize build
@build = build
end
def process
@build.in_progress!
@result = ''
preparation = prepare_files && check_requirements && prepare_libs && prepare_gems
okay = preparation
spec_start_time = nil
if prepar... |
require "rails_helper"
RSpec.describe SyndromesController, type: :routing do
describe "routing" do
it "routes to #index" do
expect(:get => "/syndromes").to route_to("syndromes#index")
end
it "routes to #new" do
expect(:get => "/syndromes/new").to route_to("syndromes#new")
end
it "r... |
module ZeroDowntimeMigrations
class Validation
class AddReference < Validation
def validate!
return if !migration.index? || migration.safe?
error!(message)
end
private
def message
<<-MESSAGE.strip_heredoc
Adding a non-concurrent index is unsafe whilst addi... |
class CartsController < ApplicationController
before_action :authenticate_user!
protect_from_forgery
# userの買い物カゴを見る
def show
@total_price = 0
@carts = current_user.carts.where(settled: false)
@carts.each { |cart| @total_price += cart.product.price_tax_included }
if @carts.empty?
flash[:a... |
# 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... |
class MessageSerializer < ActiveModel::Serializer
belongs_to :whale, foreign_key: :whale_id
belongs_to :chatroom, foreign_key: :chatroom_id
attributes :id, :content
end
|
class CommentsController < ApplicationController
# submits a comment about a particular product
def create
@user = User.find(session[:user_id])
@product = Product.find(params[:id])
@comment = Comment.new(content: params[:content], user: @user, product: @product)
if !@comment.save
flash[:errors... |
RSpec.describe 'include matcher' do
context 'hot chocolate' do
it 'checks for substring inclusion' do
expect(subject).to include('choco')
end
it { is_expected.to include('cho') }
end
it { is_expected.to include('clude') }
context [10, 20, 30] do
it { is_expected.to include(20) }
end
... |
class AddOathExpirationToUser < ActiveRecord::Migration
def change
add_column :users, :oath_expires_at, :datetime, :default => Time.now
end
end
|
module Cultivation
class ValidateSeed
prepend SimpleCommand
attr_reader :args
def initialize(args = {})
@args = args
end
def call
save_record
end
private
def save_record
batch = Cultivation::Batch.find(args[:batch_id])
catalogue_id = Inventory::Catalogue.se... |
module ActiveJob
# == Active Job adapters
#
# Active Job has adapters for the following queueing backends:
#
# * {Backburner}[https://github.com/nesquena/backburner]
# * {Delayed Job}[https://github.com/collectiveidea/delayed_job]
# * {Qu}[https://github.com/bkeepers/qu]
# * {Que}[https://github.com/cha... |
#!/usr/bin/env ruby
scripts = ["gitdbdump","dpkg-origins","dpkg-purge","mail2group"]
target = "/usr/local/bin/"
dir = File.dirname(File.expand_path(__FILE__))
scripts.each do |script|
link_from = File.join(target,script)
link_to = File.join(dir,script)
puts "symlinking #{link_from} to #{link_to}"
beg... |
# 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... |
require "spec_helper"
describe ReschedulingsController do
describe "routing" do
it "routes to #index" do
get("/reschedulings").should route_to("reschedulings#index")
end
it "routes to #new" do
get("/reschedulings/new").should route_to("reschedulings#new")
end
it "routes to #show" d... |
class Scenario < ApplicationRecord
has_many :records, dependent: :destroy
has_many :steps, dependent: :destroy
has_one_attached :image
def image_url
if image.attachment.nil?
return 'http://lorempixel.com/100/100'
else
return image.blob.service_url
end
end
end
|
# frozen_string_literal: true
# lists users keys
class List
class << self
def user_exist?(iam, username)
iam.get_user(user_name: username)
rescue Aws::IAM::Errors::NoSuchEntity
return false
end
def process_keys(user_keys, account, username)
unless user_keys.access_key_metadata.empt... |
class Block < ActiveRecord::Base
has_many :boulders
belongs_to :sector
end
|
# frozen_string_literal: true
require 'common/models/base'
module Preneeds
class State < Common::Base
attribute :code, String
attribute :name, String
attribute :first_five_zip, String
attribute :last_five_zip, String
attribute :lower_indicator, String
def id
code
end
# Defaul... |
class AnnounceMailer < ActionMailer::Base
def job_board_digest()
now = Time.now
start = now - (now.wday * 60*60*24) # Sunday starts the week (wday=0 for sunday)
@subject = "Vancouver Job Board Digest Week #{now.week} Starting #{start.strftime( '%B/%d' )}"
@body = { :posts => Po... |
Rails.application.routes.draw do
get 'artists/index'
get 'artists/show'
resources :artists, only: [:index, :show]
root 'songs#index'
match 'songs', to: 'songs#index', via: 'get'
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
|
# abstract
class Beverage
Sizes = [:small, :standard, :big]
@description = "Unknown bewerage"
@size = "Unknown Size"
def get_description
@description
end
def set_size(size = Sizes[1])
@size = size
end
def get_size
size
end
def cost
# abstract
raise "# abstract: (cost) Should ... |
class Admin::BaseController < ApplicationController
before_action :admin_authorize
def self.local_prefixes
[controller_path, 'admin']
end
def admin_authorize
if @user_nurse.id != Nurse.first.id
flash[:warning] = 'Only admin nurses are able to access this action/page'
redirect_to login_url
... |
class CreateEventParticipants < ActiveRecord::Migration
def change
create_table :event_participants do |t|
t.belongs_to :user
t.belongs_to :event
t.string :telephone, :limit => 64, :null => false
t.string :email, :limit => 64, :null => false
t.text :note
t.string :username, :li... |
class ListingsController < ApplicationController
def new
@listing = Listing.new
end
def create
@listing = Listing.new(listing_params)
@listing.user_id = current_user.id
if @listing.save
redirect_to listings_path
else
render :new
end
end
def index
# results = Listing.s... |
PUBLIC_KEY = ENV['PUBLIC_KEY_PATH'] || ''
PRIVATE_KEY = ENV['PRIVATE_KEY_PATH'] || ''
if File.exist?(PUBLIC_KEY) ^ File.exist?(PRIVATE_KEY)
fail 'Need to supply both public and private key to sign GEMs!'
end
sign_gems = File.exist?(PUBLIC_KEY) && File.exist?(PRIVATE_KEY)
MAJOR_VERSION = '1.0'
MINOR_VERSION = ENV['... |
class Answer < ActiveRecord::Base
belongs_to :user
belongs_to :question
validates_presence_of :user_id, :question_id, :text
end
|
class TweetGadget
include Gadget
def title
'Twitter'
end
def entries
@entries ||= Tweet.where(user_id: user.id, deleted: false).order(:tweet_id)
end
end |
##----------------------------------------------------------------------------##
## Common Bubble Pop-ups
## Created by Neon Black
##
## For both commercial and non-commercial use as long as credit is given to
## Neon Black and any additional authors. Licensed under Creative Commons
## CC BY 3.0 - http://creativecommo... |
class AddCurrencyTypeToCurrencies < ActiveRecord::Migration[5.1]
def change
add_column :currencies, :currency_type, :string
end
end
|
class RenameGroupIdToJoinableIdOnMemberships < ActiveRecord::Migration
def self.up
rename_column :memberships, :group_id, :joinable_id
end
def self.down
rename_column :memberships, :joinable_id, :group_id
end
end
|
require 'test_helper'
class ConfigurationTest < Minitest::Test
def test_ensure_upload_configured!
config = Humidifier::Configuration.new
error =
assert_raises RuntimeError do
config.ensure_upload_configured!(payload(identifier: 'foobar'))
end
assert_match(/foobar/, error.message)
e... |
module Skore
module Request
class Collection
attr_reader :response, :resources
def initialize(response)
@response = response
end
def all
response.parsed_response
end
def current_page
response.headers['current-page'].to_i
end
def total_pag... |
#!/usr/bin/ruby
# frozen_string_literal: true
# String extension methods
class NilClass
def empty?
true
end
end |
class AddIndexesToUserAssociations < ActiveRecord::Migration
def change
add_index :user_associations, :user_id
add_index :user_associations, [:group_id, :group_type]
end
end
|
Factory.sequence :username do |n|
"#{Faker::Name.first_name.downcase}#{n}"
end
Factory.define :user do |user|
user.login { Factory.next(:username) }
user.name Faker::Name.name
end
Factory.define :driver do |driver|
driver.username { Factory.next(:username) }
driver.name Faker::Name.name
driver.team Fake... |
class RedirectURI < ApplicationRecord
self.table_name = 'redirect_uris'
belongs_to :consumer
validates :uri, uniqueness: { scope: [:consumer_id] }
end
|
class AddBreakfastSalesToInventory < ActiveRecord::Migration
def change
add_column :inventories, :breakfast_sales, :decimal
end
end
|
# to_s
# the to_s method is called automatically when puts is invoked
# it's also called automatically in string interpolation
# every class has a to_s method – inherited from Object (actually Kernel)
# can be overridden.
# The overriding will only have an effect if the return value of the overriding method is a strin... |
require File.dirname(__FILE__) + '/../spec_helper'
describe DocumentoInteresController do
describe "route generation" do
it "should map { :controller => 'documento_interes', :action => 'index' } to /documento_interes" do
route_for(:controller => "documento_interes", :action => "index").should == "/documen... |
# frozen_string_literal: true
# Loads data from Spotify to database
class LoadSongFromSpotify
extend Dry::Monads::Either::Mixin
extend Dry::Container::Mixin
register :retrieve_search_and_songs_data, lambda { |params|
if Search.find(input: params)
Left(Error.new(:already_exist, 'Search already exist'))... |
# frozen_string_literal: true
module Vedeu
# Provides various models which Vedeu uses.
#
module Models
end # Models
# :nocov:
# See {file:docs/events/focus.md#\_focus_by_name_}
Vedeu.bind(:_focus_by_name_) { |name| Vedeu.focus_by_name(name) }
# See {file:docs/events/focus.md#\_focus_next_}
Vedeu... |
json.array!(@donors) do |donor|
json.extract! donor, :id, :first_name, :last_name, :email, :push_reg_id, :locked, :note, :date_of_last_donation
json.url donor_url(donor, format: :json)
end
|
################################################################################
#
# Author: Zachary Patten <zachary@jovelabs.com>
# Copyright: Copyright (c) 2012-2013 Jove Labs
# License: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use th... |
# frozen_string_literal: true
require "set"
module GraphQL
class Subscriptions
# Serialization helpers for passing subscription data around.
# @api private
module Serialize
GLOBALID_KEY = "__gid__"
SYMBOL_KEY = "__sym__"
SYMBOL_KEYS_KEY = "__sym_keys__"
TIMESTAMP_KEY = "__timestamp... |
class Daemon < ActiveRecord::Base
extend ActiveSupport::Memoizable
include CommandLine
validates_presence_of :ctl_name
validates_uniqueness_of :ctl_name, :on => :create, :message => "must be unique"
PID_DIR = "#{RAILS_ROOT}/tmp/pids"
FILE_DIR = "#{RAILS_ROOT}/lib/daemons"
LOG_DIR = "#{RAILS_ROOT}/log"
... |
class Array
def deep_dup
self.map do |child_element|
if !child_element.is_a? Array
child_element
elsif self.no_child_array?
child_element.dup
else
child_element.deep_dup
end
end
end
def no_child_array?
return false if !self.all? { |x| !(x.... |
require "sensu/extension"
require 'uri'
require 'net/http'
require 'net/https'
require 'json'
module Sensu
module Extension
class Alertonce < Filter
@@extension_name = "alert_once"
def name
@@extension_name
end
def description
"Filter events using event occurrences & s... |
class Api::V1::UsersController < ApplicationController
def index
return nil if User.all.empty?
render json: UserSerializer.new(User.all)
end
def show
return nil if !User.exist?(params[:id])
render json: UserSerializer.new(User.find(params[:id]))
end
def create
user = User.from_onmiauth(u... |
module CCS
module FM
# -----------------
# facilities_management_buildings
class Lift < ApplicationRecord
# self.table_name = 'fm_lifts'
def self.table_name_prefix
'fm_'
end
# CCS::FM::Lift.all
#
def self.lifts_for_user(user_id)
where("user_id = '" + Ba... |
class Flag < ActiveRecord::Base
belongs_to :user
belongs_to :flaggable, :polymorphic => true, :counter_cache => true
def self.flag_types
['spam', 'abuse', 'urgent', 'other']
end
def self.valid_flag_type? flag_type
self.flag_types.index(flag_type.downcase).nil? ? false : true
end
end
|
#!/usr/bin/env ruby
#
# Author: rasan@nyu.edu
require 'google/apis/analytics_v3'
require 'googleauth'
require 'googleauth/stores/file_token_store'
require 'fileutils'
require 'thor'
require_relative './config'
require_relative './util'
require_relative './writer'
##
# Ensure valid credentials, either by restoring fr... |
# Generated by hyrax:models:install
class FileSet < ActiveFedora::Base
property :area_of_interest, predicate: ::RDF::Vocab::EXIF.subjectLocation, multiple: false
include ::Hyrax::FileSetBehavior
include MicroserviceMinter
include ::CommonIndexer::Base
before_save :impute_area_of_interest
def to_common_in... |
require 'rails_helper'
RSpec.describe AuctionsController, type: :controller do
let(:auction) {FactoryGirl.create(:auction)}
# def valid_auction
# auction :create, params: { auction: attributes_for(:auction) }
# end
# NEW ACTION TEST
describe '#new' do
it 'renders new template' do
get :new
... |
class UserMailer < ActionMailer::Base
default :from => "taskdeckmailer@gmail.com"
def registration_confirmation(user)
@user = user
mail(:to => user.email, :subject => "Registration Complete!")
end
def team_requested(user, teamleader)
@user = user
@teamleader = teamleader
mail(:to => ... |
require "card_deck"
#If we recreate a black jack game, we can then install our own
#methods of how we play and from there can configure a percentage
#that we can win :)
module PlayersDealers
def get_hand(card1, card2)
@first_card = card1
@second_card = card2
@cards_in_hand = @first_card, @second_card
en... |
require 'spec_helper'
describe Article do
let(:author) { FactoryGirl.create(:author) }
before { @article = author.articles.build(title: "Article Title 1", published: Date.today, edited: Date.yesterday) }
subject { @article }
it { should respond_to(:title) }
it { should respond_to(:author_id) }
it { shou... |
# 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... |
FactoryGirl.define do
factory :user do
name { Faker::Name.name }
email { Faker::Internet.email }
trait :with_projects do
ignore do
projects_count 2
end
after :create do |user, evaluator|
FactoryGirl.create_list :project, evaluator.projects_count, user: user
end
... |
module MessagesHelper
def last_message_with(recipient)
messages = policy_scope(Message.with(recipient)).order(created_at: :desc).first
end
def current_user_has_new_messages_from?(user)
last_message_with(user).present? && last_message_with(user).recipient == current_user && !last_message_with(user).read?
... |
module GoldPoints
module V1
class RecordsAPI < Grape::API
helpers do
def record_params
declared(params, include_missing: false)[:record].symbolize_keys
end
end
desc 'Create a new record'
params do
requires :record, type: Hash do
requires :group,... |
source 'https://rubygems.org'
gem 'rails', '4.2.5'
gem 'bootstrap-sass', '~> 3.3.6'
gem 'sass-rails', '>= 3.2'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.1.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby
gem 'jquery-rails'
gem 'turbolinks'
g... |
# Write a method that takes a string as argument, and returns true if all
# parentheses in the string are properly balanced, false otherwise.
# To be properly balanced, parentheses must occur in matching '(' and ')' pairs.
# LS Solution:
# def balanced?(string)
# parens = 0
# string.each_char do |char|
# ... |
WIN_COMBINATIONS = [ # define the win combinations as constants
[0,1,2],
[3,4,5],
[6,7,8],
[0,4,8],
[2,4,6],
[0,3,6],
[1,4,7],
[2,5,8]
]
def display_board(board) # displays the board
puts " #{board[0]} | #{board[1]} | #{board[2]} "
puts "---... |
class Notifier < ActionMailer::Base
ActionMailer::Base.default_url_options[:host] = Site.config["host"]
default :from => Site.config["from"]
def password_reset_instructions(user)
@user = user
mail(:to => user.email, :subject => "Password Reset Instructions")
end
def activation_instructions(us... |
Ohai.plugin(:Lsyncd) do
provides 'lsyncd'
def find_lsyncd_bin
unless @lsyncd_bin
so = shell_out("/bin/bash -c 'command -v lsyncd'")
lsyncd_bin = so.stdout.strip
end
return lsyncd_bin unless lsyncd_bin.empty?
end
def find_lsyncd_process(lsyncd_command)
unless @lsyncd_process
c... |
# frozen_string_literal: true
class AddShortDescriptionToFacilities < ActiveRecord::Migration
def self.up
add_column :facilities, :short_description, :text, null: false
end
def self.down
remove_column :facilities, :short_description
end
end
|
# frozen_string_literal: true
FactoryBot.define do
factory :account do
type { "Account" }
sequence(:account_number) { |n| n }
description { "Account description" }
expires_at { 50.years.from_now }
created_by { 0 }
end
trait :with_account_owner do
transient do
owner { FactoryBot.cre... |
module AssetifyHelper
def assetify_javascript_library_include_tag(library = "library", options = {})
asset = "/assets/#{library}.js"
fix_rails_asset_cache(asset)
javascript_include_tag(asset)
end
def assetify_javascript_dynamic_include_tag(options = {})
cont = options.delete(:controller) || ... |
require_relative 'human'
require_relative 'computer'
require_relative 'game_methods'
class Game
attr_accessor :board
attr_reader :com, :hum
include GameMethods
def initialize
@board = ["0", "1", "2", "3", "4", "5", "6", "7", "8"]
@com = "X"
@hum = "O"
end
def start_game
puts "Welcom... |
# frozen_string_literal: true
require 'fastlane/action'
require_relative '../helper/debug_file_helper'
module Fastlane
module Actions
module SharedValues
DF_PROGUARD_ZIP_PATH = :DF_PROGUARD_ZIP_PATH
end
class ProguardAction < Action
MATCHES_FILES = {
mapping: {
name: 'mapp... |
class ProducersController < ApplicationController
before_action :authenticate_user!, only: [:new, :create]
before_action :admin_user, only: [:new, :create]
before_action :logged_in_producer, only: [:edit, :update]
before_action :correct_producer, only: [:edit, :update]
def index
@areas = Area... |
require 'test/unit'
require './hangman.rb'
class TestHang < Test::Unit::TestCase
def setup
@words = words_length(load_dictionary)
end
def test_correct_length
assert @words.all? { |word| word.length >= 5 && word.length <= 12 }
end
end |
require 'yaml'
require 'date'
def last_monday(date_in)
case date_in.wday
when 1..6
date_in - (date_in.wday - 1)
when 0
date_in - 6
end
end
def load_config(file = "config/config.yaml")
YAML::load_file(File.join($app_root, file))
end
def save_lastrun(config, file = load_config['lastrun_file'])
File... |
require 'fog/collection'
require 'fog/aws/models/ec2/image'
module Fog
module AWS
class EC2
class Images < Fog::Collection
attribute :image_id
model Fog::AWS::EC2::Image
def initialize(attributes)
@image_id ||= []
super
end
def all(image_id =... |
class CreateAlbums < ActiveRecord::Migration
def change
create_table :albums do |t|
t.string :title
t.text :description
t.datetime :year
t.integer :artist_id
t.string :art
t.timestamps
end
add_column :songs, :album_id, :integer
end
end
|
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{redis-model}
s.version = "0.1.3"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :requir... |
require 'rails_helper'
require 'category.rb'
require 'product.rb'
RSpec.describe Product, type: :model do
before do
@toy_category = Category.new(name: 'toys')
end
describe 'Validations' do
it 'should throw the correct error if it is instantiated without a name' do
@new_product = Product.new(nam... |
class ChapterAction < ActiveRecord::Base
has_many :chapter_action
belongs_to :chapter
end
|
class TreasureDecorator < Draper::Decorator
delegate_all
def description
if object.description.present?
h.truncate(object.description, length: 42)
else
I18n.t('no_description')
end
end
def name
h.truncate(object.name, length: 18)
end
def created_at
l object.created_at, for... |
# frozen_string_literal: true
require "test_helper"
class FetchMohfwTest < ::ActiveSupport::TestCase
test "download from the mohfw api" do
record_options = { record: :none, match_requests_on: %i[uri] }
VCR.use_cassette("mohfw", record_options) do
assert_difference "::Job.count" => 1, "::DataSnapshot.c... |
require 'minitest/autorun'
require 'minitest/pride'
require './lib/node'
class NodeTest < Minitest::Test
def test_node_exists
node = Node.new("Burke")
assert_instance_of Node, node
end
def test_if_has_surname
node = Node.new("Burke")
assert_equal "Burke", node.surname
end
def test_if_next... |
class OtherKakeibosController < ApplicationController
def new
@other_kakeibo = OtherKakeibo.new
@kakeibo = Kakeibo.where(is_kakeibo_status: 0, user_id: current_user.id)
end
def create
@other_kakeibo = OtherKakeibo.new(other_kakeibo_params)
@other_kakeibo.user_id = current_user.id
if @other_ka... |
execute 'Install td-agent' do
# See http://docs.fluentd.org/articles/install-by-rpm
command 'curl -L http://toolbelt.treasuredata.com/sh/install-redhat-td-agent2.sh | sh'
not_if 'rpm -q td-agent'
end
service 'td-agent' do
action [:enable, :start]
supports restart: true, reload: true, status: true
end
|
namespace :dev do
task deployed: :environment do
%w[db:migrate db:seed db:seed:bodybuilding dev:update_entries_data_model].each do |name|
Rake::Task[name].reenable
Rake::Task[name].invoke
end
end
task rename_icons: :environment do
Dir['app/assets/images/icons/*.png'].each do |icon_name|
... |
require 'spec_helper'
require 'rails_helper'
feature 'sign in' do
scenario 'user signs in successfully' do
user = FactoryGirl.create(:user, email: "snape@slytherin.com")
visit root_path
click_link "Login"
fill_in "Email", with: "snape@slytherin.com"
fill_in "Password", with: "HarryPotter"
cli... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.