text stringlengths 10 2.61M |
|---|
require 'json'
require 'sinatra/base'
require 'sinatra/respond_with'
class FortuneApp < Sinatra::Base
register Sinatra::RespondWith
set :app_path, '/fortune'
get '/?:long?/?:dirty?' do
args = '-'
command = ['fortune']
long = params[:long].to_i
dirty = params[:dirty].to_i
case long
w... |
class CommentsController < ApplicationController
before_action :authenticate_usermodel!
def create
@stay = Stay.find(params[:stay_id])
@stay.comments.create(comment_params.merge(:usermodel => current_usermodel))
redirect_to stay_path(@stay)
end
private
def comment_params
params.require(:comment).permit(:... |
require_relative 'adjacency_list_builder/extended_integer'
class AdjacencyListBuilder
def initialize(n, graph_string)
@n = n # node count
@graph_string = graph_string
@adjacency_list = Array.new(n) { [] }
end
def call(directed: false)
parsed_graph_string.each do |tuple|
# first element is ... |
require 'rails_helper'
require 'rake'
Dir[Rails.root.join('lib/tasks/**/*.rb')].each { |f| require f }
describe 'Data' do
before do
load File.expand_path("../../../lib/tasks/data.rake", __FILE__)
Rake::Task.define_task(:environment)
allow(Rails.cache).to receive(:clear)
end
describe '#import' do
... |
class OtherKakeibo < ApplicationRecord
belongs_to :user
belongs_to :kakeibo
validates :object, presence: true
validates :billing_amount, presence: true
end
|
#!/usr/bin/env ruby
require 'spec_helper'
libpcrecpp_pkg_name = ''
describe 'default packages & settings for Ubuntu 14.04', if: os[:release].to_i == 14 do
libpcrecpp_pkg_name = 'libpcrecpp0'
end
describe 'default packages & settings for Ubuntu 15.10', if: os[:release].to_i == 15 do
libpcrecpp_pkg_name = 'libpcr... |
class User < ApplicationRecord
attr_accessor :registration_password, :registration_password_repeat
validates :email_addr, :passwd, :first_name, :last_name, :phone, presence: true
validates :email_addr, uniqueness: true
def evaluate_registration
if registration_password != registration_password_repeat
... |
class MyEquipement < ApplicationRecord
belongs_to :user
belongs_to :equipement
end
|
module Portalgun
class Portal
class Host
class OperatingSystem
class Network
attr_accessor :name
attr_accessor :subnet
attr_accessor :netmask
attr :devices
def initialize
@devices = Array.new
end
def add_device... |
include Kytoon
namespace :kytoon do
TMP_SG=File.join(KYTOON_PROJECT, 'tmp', 'server_groups')
directory TMP_SG
task :init => [TMP_SG] do
ServerGroup.init(ENV['GROUP_TYPE'])
end
desc "Create a new group of servers"
task :create => 'kytoon:init' do
sg = ServerGroup.create(ENV['GROUP_CONFIG'])
... |
# :nodoc:
require 'test/unit'
require 'test/unit/testcase'
require File.join(File.dirname(__FILE__), '..', 'examples', 'corpus')
class TestCorpus < Test::Unit::TestCase
def test_regular_corpus
c = Corpus[:HBD]
assert_equal('E:\OfficeDateien\Corpus/Java6_Web(HBD_Online)', c.location)
assert_equal('E:\Of... |
require './spec/spec_helper.rb'
describe 'Languages' do
self.use_transactional_fixtures = false
before :all do
ensure_server_is_running
DatabaseCleaner.clean
end
after :all do
DatabaseCleaner.clean
end
describe 'Category CRUD' do
it 'should be editable' do
ensure_logged_in_as 'ad... |
# frozen_string_literal: true
require 'yaml'
require_relative '../lib/styled_yaml'
RSpec.describe StyledYAML do
jabberwocky = 'Beware the Jabberwock, my son!'
walrus = [
'The sun was shining on the sea,',
'Shining with all his might:',
'He did his very best to make',
'The billows smooth and brigh... |
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Registration do
let(:user) { create(:user) }
let(:event) { create(:event) }
before { generic_seo_and_ao }
describe '.not_refunded' do
let!(:normal) { create(:registration, :with_email) }
let!(:refunded) do
create(:registration... |
# frozen_string_literal: true
module FacebookAds
# https://developers.facebook.com/docs/marketing-api/reference/ad-account
class AdAccount < Base
FIELDS = %w[id account_id account_status age created_time currency name].freeze
class << self
def all(query = {})
get('/me/adaccounts', query: que... |
require("minitest/autorun")
require("minitest/rg")
require_relative("../food")
class FoodTest < MiniTest::Test
def setup
@banana = Food.new("Banana", 1)
end
def test_rejuvination_level
assert_equal(1, @banana.rejuvination_level)
end
end
|
require 'spec_helper'
require 'tackle_box/email/template/tags/attachment'
describe TackleBox::Email::Template::Tags::Attachment do
subject { Liquid::Template.parse('{% attachment %}') }
let(:attachment) { 'foo.zip' }
context "when 'attachment' is set" do
let(:context) do
Liquid::Context.new({'attach... |
remote_file '/root/flink.tgz' do
source 'http://apache.lauf-forum.at/flink/flink-1.3.1/flink-1.3.1-bin-hadoop27-scala_2.10.tgz'
not_if { ::Dir.exists?('/root/flink.tgz') }
end
user 'flink' do
manage_home true
end
execute 'extract flink' do
command 'tar xvf /root/flink.tgz -C /home/flink'
not_if '[ $(ls /h... |
class Team
attr_accessor :name , :motto, :heroes
@@all = []
def initialize(attribute)
@heroes = []
attribute.each do |k,v|
self.send("#{k.to_s}=",v)
end
end
def self.all
@@all
end
end
|
require 'rails_helper'
RSpec.describe Post, :type => :model do
context "association" do
it { should belong_to(:user) }
end
context "validations" do
it { should validate_presence_of(:title) }
it { should validate_presence_of(:content) }
it { should validate_presence_of(:slug) }
it { should va... |
# Class Warfare, Validate a Credit Card Number
# I worked on this challenge [by myself, with: ].
# I spent [#] hours on this challenge.
# Pseudocode
# Input: 16-digit number
# Output: "Profit"
# Steps:
# initialize class with number that equals 16 digits, else return ArgumentError
# step 1 should double every othe... |
class CreateMenuPages < ActiveRecord::Migration
def self.up
create_table :menu_pages do |t|
t.integer :menu_id
t.integer :page_number
t.string :repository_uuid
t.string :catalog_number
t.timestamps
end
end
def self.down
drop_table :menu_pages
end
end
|
# frozen_string_literal: true
RSpec.describe 'grant features' do
after(:all) do
ActiveRecord::Migration.drop_table :widgets
end
before(:all) do
ActiveRecord::Migration.create_table :widgets, force: true do |t|
t.string :name, default: nil, required: false
end
end
class Widget < Applicatio... |
hostname = "dev.lcl"
db_name = "symfony"
server_ip = "192.168.10.10"
server_memory = "768" # MB
server_timezone = "Australia/Sydney"
mysql_version = "5.6" # Options: 5.5 | 5.6
php_version = "latest" # Options: latest|previous|distributed For 1... |
module BtcController
require 'csv'
require './Helpers/btc_math_helper.rb'
require './Helpers/btc_view_helper.rb'
require './Models/btc_double_spend.rb'
require './Models/btc_block_survival.rb'
require './Models/btc_duration.rb'
include BtcViewHelper
include BtcDuration
def path_prefix
"./Views/HTML/CSV/"
... |
require './my_shoppingcart'
describe MyShopppingCart::ShoppingCart do
let(:products) { subject.import_products('./test_data/products.json') }
let(:item1) { products.first }
before do
subject.add_item(item1.uuid)
end
it "shoppingcart has one item" do
expect(subject.line_items.count).to eql 1
... |
class Student < ActiveRecord::Base
attr_accessible :date_of_birth, :family_name, :given_name, :grade_point_average, :middle_name, :start_date
has_many :awards, :dependent => :destroy
has_and_belongs_to_many :courses
def name
given_name + " " + family_name
end
def enrolled_in?(course)
self.courses.... |
class CoursesController < ApplicationController
def index
courses = Course.all
render json: courses, status: 200
end
def show
course = Course.find(params[:id])
render json: course, status: 200
end
def create
course = Course.new(title: course_params[:title])
if course.save
# если ... |
class NFL < Player
include Initialer
def name_brief
[first_initial, last_name].compact.join ' '
end
end
|
FactoryGirl.define do
factory :component do
sequence(:component) { Faker::App.name }
sequence(:position) { |n| (n%3)+1 }
selected false
trait :of_line_item do
composable_type "LineItem"
composable_id nil
end
factory :component_of_line_item, traits: [:of_line_item]
end
end
|
require 'test_helper'
require "uber/builder"
class BuilderTest < MiniTest::Spec
Evergreen = Struct.new(:title)
Hit = Struct.new(:title)
class Song
include Uber::Builder
builds do |options|
if options[:evergreen]
Evergreen
elsif options[:hit]
Hit
end
end
def s... |
class AddIndexToSmsMessage < ActiveRecord::Migration
def self.up
add_index :sms_messages, :automated_message, :name => "index_by_automated_message"
add_index :sms_messages, :message_type, :name => "index_by_message_type"
end
def self.down
remove_index :sms_messages, :name => "index_by_automated_mess... |
class Course < ActiveRecord::Base
has_many :user_courses, dependent: :destroy
has_many :users, through: :user_courses
has_many :course_subjects, dependent: :destroy
has_many :subjects, through: :course_subjects
end
|
class Matrix
def matrix_product(first, second)
if first == nil || second == nil || first[0].length != second.length
return nil
end
result = Array.new(first.length) { [0] * second[0].length }
for i in 0...result.length
for j in 0...result[0].length
for k in 0...first[0].length... |
# Copyright 2014 Square 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.0
#
# Unless required by applicable law or agreed ... |
# Grandfather clock. Write a method that takes a block and calls it once for
# each hour that has passed today. That way, if I were to pass in the block:
# do
# puts 'DONG!'
# end
# it would chime (sort of) like a grandfather clock. Test your method out
# with a few different blocks.
# Hint: You can use Time.new.hour t... |
class State < ApplicationRecord
STATES = %w(completed, not_completed)
belongs_to :habit
end
|
# frozen_string_literal: true
module SXS
module Publishers
class Redis
require 'redis'
def initialize(queue_url)
@queue_url = queue_url
end
def publish(body)
redis.rpush @queue_url, body
end
private
def redis
@redis ||= ::Redis.new(::SXS.confi... |
class Pledge < ActiveRecord::Base
belongs_to :funding_level
belongs_to :project
validates :funding_level, :presence =>true
validates :name, :presence =>true
validates :email, :presence => true
validates :amount, numericality: { greater_than: 0 }
end
|
class SiteHotelsController < ApplicationController
before_action :set_site_hotel, only: %i[ show edit update destroy ]
before_action :find_site
# GET /site_hotels
def index
if @site.nil?
@site_hotels = SiteHotel.all
else
@site_hotels = SiteHotel.where("site_id = ?" , @site)
end
end... |
Yuko.configure do |config|
# IRC Informations:
config.irc.server = 'irc.smoothirc.net'
config.irc.port = 6667
config.irc.ssl = false
config.irc.channel = '#mangas'
config.irc.nickname = 'Yuko'
config.irc.greeting = 'Yuko kuruyo~ https://youtu.be/cIkoZbvTfwc \o/'
# MyAnimeList Account:
co... |
class ProductDatatable
delegate :current_user, :content_tag, :check_box_tag, :params, :link_to, :number_to_currency, :calculate_cost, :number_to_percentage, to: :@view
delegate :url_helpers, to: 'Rails.application.routes'
delegate :session, to: :@view
include ApplicationHelper
def initialize(view)
@view... |
#Attr Methods
# I worked on this challenge by myself
# I spent [1] hours on this challenge.
class NameData
attr_accessor :name
def initialize
@name = 'Kurt'
end
end
class Greetings
def initialize
@nameInstance = NameData.new
end
def hello
puts "Hello #{@nameInstance.name}, welcome to the wor... |
# Read about factories at http://github.com/thoughtbot/factory_girl
FactoryGirl.define do
factory :task do
sequence(:description) { |n| "Task#{n}" }
sequence(:duedate) { |n| "7/1#{n}/2#{n}1#{n}" }
taskable_id 1
taskable_type "MyString"
association :taskable, factory: :todouser
association :ta... |
class Announcement < ActiveRecord::Base
validates_presence_of :title
validates_format_of :url, :with => /\Ahttp(s?):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/i, :message => "should look like a URL", :allow_blank => true
end
|
# frozen_string_literal: true
class UniformNotifier
class Raise < Base
class << self
def active?
defined?(@exception_class) ? @exception_class : false
end
def setup_connection(exception_class)
@exception_class = exception_class == true ? Exception : exception_class
end
... |
module YoutubeMultipleDL
class Delayed::Job
def self.ordered
order("priority ASC")
end
def self.current
where("locked_at IS NOT NULL")
end
def self.failed
where("locked_at IS NULL AND last_error IS NOT NULL")
end
def self.queued
where("locked_at IS NU... |
# Copyright 2007-2014 Greg Hurrell. All rights reserved.
# Licensed under the terms of the BSD 2-clause license.
require 'walrat'
module Walrat
class ParsletSequence < ParsletCombination
attr_reader :hash
# first and second may not be nil.
def initialize first, second, *others
raise ArgumentError... |
require 'rails_helper'
describe Article do
# user = User.create!(
# name: "ユニットテスト",
# email: "unit@test.com",
# password: "unittest",
# password_confirmation: "unittest"
# )
user = User.find_by(email: "unit@test.com")
subject { Article.new(
user_id: user.id,
titl... |
# frozen_string_literal: true
class Folder < ApplicationRecord
validates_with Validators::Base, fields: %i[title workspace]
has_many :ticket_folders, dependent: :destroy
has_many :tickets, through: :ticket_folders
belongs_to :workspace
def tickets_positions(except: nil)
tickets.where.not(id: except).pl... |
FactoryBot.define do
factory :client_status do
sequence(:name) { Faker::Lorem.unique.word }
followup_date { nil }
icon_color { "\##{SecureRandom.hex(3)}" }
department do
create :department
end
end
end
|
# frozen_string_literal: true
require 'faraday'
require 'octokit'
require 'faraday-http-cache'
require 'active_support/cache'
require 'active_support/cache/file_store'
stack = Faraday::RackBuilder.new do |builder|
storer = ActiveSupport::Cache::FileStore.new('/tmp', namespace: 'pullrequest')
builder.use Faraday::... |
FactoryBot.define do
factory :game do
home_team { 'CHN' }
away_team { 'CHA' }
game_year { '2016' }
park { 'CHN' }
home_homeruns {}
away_homeruns {}
day_of_week { 'Wednesday' }
month { 'August' }
season { FactoryBot.create(:season) }
# not sure line above works
# add more he... |
class Position
include Mongoid::Document
include Mongoid::Timestamps # adds created_at and updated_at fields
include Tire::Model::Search
include Tire::Model::Callbacks
field :company, type: String
field :position, type: String
field :location, type: String
field :skills, type: Array
... |
# -*- coding: utf-8 -*-
require 'bundler'
Bundler.setup
require 'rubytter'
autoload :Sequel, 'sequel'
EGOTTER_ROOT = File.join(File.dirname(File.expand_path(__FILE__)), '..')
$: << EGOTTER_ROOT
require 'lib/egotter/account'
require 'lib/egotter/client'
include Egotter
module Egotter
class EgotterError < Standard... |
require 'rails/all'
require 'active_record_batteries'
ActiveRecord::Base.establish_connection(:adapter => 'sqlite3', :database => ':memory:')
ActiveRecord::Schema.verbose = false
ActiveRecord::Schema.define do
self.verbose = false
create_table :authors do |t|
t.string :name
# Sluggable
t.string :slu... |
module HasModerated
module Associations
module Collection
module AssociationPatches
# moderate adding associations
def add_to_target_with_moderation record
# If create is moderated, then add assoc. record normally, as create moderation
# will prevent AR from creating the ... |
class PostsController < ApplicationController
before_action :authenticate_user!, except: [:index, :show]
#display all blogs at the index fle
def index
@posts = Post.all.order('created_at DESC')
end
#to add new posts
def new
@post = Post.new
end
def create
@post = Post.new(post_params)
if @post.... |
class Invoice < ActiveRecord::Base
belongs_to :account
has_many :line_items, :class_name => 'InvoicesLineItem'
has_many :invoices_payments
has_many :payments, :through => :invoices_payments
def total
line_items.inject(0) do |sum, li|
sum + li.amount
end
end
def paid
payments.inject(0) ... |
class AddProfileInformationtoUser < ActiveRecord::Migration[5.0]
def change
add_column :users, :location, :string
add_column :users, :occupation, :string
add_column :users, :age, :integer
add_column :users, :self_summary, :text
end
end
|
require 'test_helper'
class WeeklyMenusControllerTest < ActionDispatch::IntegrationTest
setup do
@weekly_menu = weekly_menus(:one)
end
test "should get index" do
get weekly_menus_url
assert_response :success
end
test "should get new" do
get new_weekly_menu_url
assert_response :success
... |
class CreateOrders < ActiveRecord::Migration
def self.up
create_table :orders do |t|
t.string :state
t.integer :lock_version
t.text :info
t.float :total_money
t.float :fright_money
t.float :total_item_money
t.float :favorable_money
t.string :payment_info
t.ti... |
require 'spec_helper'
describe QuotesController, type: :controller do
context 'GET index' do
before(:each) do
Quote.delete_all
end
let!(:quote) { Quote.create!(quote: 'Test quote', author: 'Rspec') }
before do
get :index
end
it 'should assign quote' do
expect(assigns(:quo... |
# frozen_string_literal: true
class Item < ApplicationRecord
belongs_to :brand
belongs_to :item_name
belongs_to :model
belongs_to :color
belongs_to :size
has_one_attached :image
has_many :orders
has_many :deals
# extend FriendlyId
# friendly_id :name, use: :slugged
def slug_items
[
:... |
require 'json'
file = File.read('grades.json')
student = JSON.parse(file)
average_grade = student.sum{|student| student['grade']} / student.count
def failedorpassed(array,status)
array.each_with_index do |n,i|
if i <= array.count - 3
print "#{n['name']}, "
elsif i == ar... |
# frozen_string_literal: true
# a joins model between users and videos for bookmarking
class UserVideo < ApplicationRecord
belongs_to :video, foreign_key: 'video_id'
belongs_to :user, foreign_key: 'user_id'
end
|
Gem::Specification.new do |s|
s.name = "wacky_graph"
s.version = "0.1"
s.authors = ["Matt Rushton"]
s.email = ["mrushton7@yahoo.com"]
s.homepage = "http://www.wackywordsfriends.com"
s.summary = "Gem for the Facebook graph API."
s.description = "Wacky Graph is a gem extracted f... |
class TestHttpClient < BaseTest
def initialize
super
require "httpclient"
@client = HTTPClient.new
end
def bench
resp = @client.get_content(URL, nil, @headers)
verify_response(resp)
end
end
test_http("httpclient", TestHttpClient)
|
# frozen_string_literal: true
module NewDawn
Container.boot(:settings, from: :system) do
before(:init) do
require 'types'
end
settings do
key :database_url, ::Types::FilledString
end
end
end
|
class CareTakersController < ApplicationController
before_action :get_care_taker, only: [:show, :edit, :destroy, :update]
def index
@care_takers = CareTaker.all
end
def show
end
def new
@care_taker = CareTaker.new
@kid = @care_taker.kids.build(name: "name")
end
def create
@care_taker... |
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
validates :nickname, :email, :password, :password_conf... |
class MediaContactMessage < ActiveRecord::Base
attr_accessible :media_list_id, :message, :release_id, :originator
belongs_to :media_list
belongs_to :release
validates :media_list_id, :message, :release_id, :originator, presence: true
ORIGIN = { :user => 'user', :media_contact => 'media_contact' }
end
|
require 'csv'
require 'json'
namespace :db do
desc "Fill database with caldwell objects"
task caldwells: :environment do
process_caldwell
end
end
def process_caldwell
acaldwells = []
CSV.foreach("db/data/caldwells.csv", headers: true) do | row |
c = row['c']
tipo = row['Tipo']
ra = row['... |
module Api::V1
class AgentSerializer < ActiveModel::Serializer
include Rails.application.routes.url_helpers
attributes :id, :status, :version, :enabled, :heartbeat_at
has_one :jobqueue, serializer: Api::V1::JobqueueSerializer
attribute :links do
{ self: v1_agent_path(object.id) }
end
e... |
class ActorSerializer < ActiveModel::Serializer
attributes :name, :id, :imdb_id, :tmdb_id
has_many :movies
end
|
desc "Provision a store with MYHQ_STORE_COMPANY_ID=<company id>, MYHQ_STORE_USER_ID=<user id>"
task :provision_store => :environment do
begin
company = Company.find(ENV["MYHQ_STORE_COMPANY_ID"])
user = User.find(ENV["MYHQ_STORE_USER_ID"])
config = {
app_domain: company.retail_... |
require 'concurrent'
class WorkPool
def initialize(thread_count)
@thread_count = thread_count
@pool = Concurrent::FixedThreadPool.new(@thread_count)
end
def post(*args, &block)
@pool.post(*args, &block)
end
def wait_for_completion
loop do
sleep 0.5
break if @pool.queue_length ==... |
class Prodtype < ActiveRecord::Base
validates :name , :presence => true
end
|
module Battman
module DSL
class EveryBlock
def initialize(battman, battery, interval)
@battery = battery
@interval = interval
@battman = battman
@last_values = {}
end
def check(attribute, *args, &block)
raise ArgumentError.new('no block given') unless bl... |
desc "Updates balances to use Validated"
task update_balances_to_use_validated: :environment do
puts "Starting update..."
# Primero actualicemos los balances que sabemos que fueron validados
validated_balances = Balance.where("transfers_cents != 0")
.or(Balance.where("diff_cents != 0"))
.or(Balance.where... |
require 'test_helper'
Expectations do
expect "From: sender@gmail.com\nTo: to@gmail.com\nSubject: subject\nMIME-Version: 1.0\nContent-Type: text/plain\n\nbody\n" do
string_io = StringIO.new
message_stream_writer = GmailSender::MessageStreamWriter.new("sender@gmail.com")
message_stream_writer.write(string_... |
class PasswordsController < Devise::PasswordsController
protected
def after_sending_reset_password_instructions_path_for(resource_name)
if request.path == '/users/password'
root_path
else
new_vendor_session_path
end
end
def after_resetting_password_path_for(resource)
if req... |
require "rails_helper"
RSpec.feature "Spouse" do
let(:email) { 'shaanjain@gmail.com' }
let(:password) { 'password' }
let!(:family) {
Family.create!(
address: '420 Birmingham Lane',
city: 'Schaumburg',
state: 'IL',
zip: '60193'
)
}
let!(:primary_user) {
User.create!(
... |
require_relative '../automated_init'
context "Incorrect Attribute Definition" do
context "Strict without type" do
test "Incorrect" do
incorrect_attribute_definition = proc do
Class.new do
include ::Schema
attribute :some_attribute, strict: true
end
end
asser... |
require 'test_helper'
module KindleHighlightsAPI
class FetcherTest < MiniTest::Unit::TestCase
def test_fetch_returns_an_array_of_all_the_books
fetcher = Fetcher.new('some@email.com', 'password')
books = fetcher.fetch_all
assert_equal expected_book_titles, books.map(&:title)
assert_equal... |
require 'mini_magick'
module Jekyll
class OctoGallery < Liquid::Block
def initialize(tag_name, markup, tokens)
base_path = 'source/images/'
@title = markup != '' ? markup.strip : Digest::SHA1.hexdigest(tokens.join)
@images = tokens[0].strip.split("\n")
@images.map!{|line| {src: line[... |
class Travelport::Bridge::Air < Travelport::Bridge::Base
default_for :service, 'AirService'
default_for :document, 'air_v18_0/Air.wsdl'
def low_fare_search
req = Travelport::Request::LowFareSearchReq.new
yield req if block_given?
raw_content = request(req)
if req.flexible_dates
Travelport:... |
class RestaurantsController < ApplicationController
before_action :get_id
def index
district_id = get_id
if district_id != ""
@restaurants = Restaurant.where(district_id: district_id)
else
@restaurants = Restaurant.all
end
render 'index'
end
def show
@restaurant = Restauran... |
class GroupPostCommentsController < ApplicationController
before_filter :login_required
filter_access_to :create
filter_access_to :destroy,:attribute_check => true,:load_method => lambda { GroupPostComment.find(params[:id]) }
def create
@group_post=GroupPost.find(params[:group_post_id])
@group_post_comm... |
require 'spec_helper'
describe "user_profiles/show" do
before(:each) do
@user_profile = assign(:user_profile, stub_model(UserProfile,
:profile_code => "Profile Code",
:profile_name => "Profile Name",
:profile_active => false,
:profile_admin => false
))
end
it "renders attributes ... |
#
# Cookbook Name:: s3cmd
# Recipe:: default
# Frederico Araujo (fred.the.master@gmail.com)
# https://github.com/fred/chef-s3cmd
#
package "python"
package "python-setuptools"
package "python-distutils-extra"
package "python-dateutil"
package "python-requests"
remote_file "#{Chef::Config[:file_cache_path]}/master.tar... |
require 'json'
require 'faraday'
require 'typhoeus'
require 'typhoeus/adapters/faraday'
module Filepreviews
# @author Jonah Ruiz <jonah@pixelhipsters.com>
# Contains http helper module
module HTTP
API_URL = 'https://blimp-previews.herokuapp.com/'
USER_AGENT = "Filepreviews-Rubygem/#{Filepreviews::VERSION... |
# -*- coding: utf-8 -*-
module Concerns::Genre::Validation
extend ActiveSupport::Concern
included do
validates :title, presence: true, format: { without: /\A\s*\z/ }
validates :name, uniqueness: {scope: :parent_id }
validates :deletable, inclusion: { in: [true, false] }
validate :validate_name, :v... |
require 'redis'
require 'fast-filter/engine'
module FastFilter
class BitmapEngine < Engine
# The maximum bits to store in the bitmap.
# This is to prevent unbounded memory usage.
MAX_OFFSET = 9
def initialize(options = {})
options[:server] ||= {}
options[:server][:db] ||= 1
o... |
class Dessert
attr_accessor :name, :calories
def initialize(name, calories)
@name = name
@calories = calories
end
def healthy?
self.calories < 200
end
def delicious?
self.instance_of? Dessert
end
end
class JellyBean < Dessert
attr_accessor :flavor
def initialize(name, calories... |
class Reply < ActiveRecord::Base
belongs_to :ticket
belongs_to :owner
belongs_to :department
belongs_to :state
validates :body, presence: true
end
|
# Be sure to restart your server when you modify this file.
# Add new inflection rules using the following format
# (all these examples are active by default):
# Inflector.inflections do |inflect|
# inflect.plural /^(ox)$/i, '\1en'
# inflect.singular /^(ox)en/i, '\1'
# inflect.irregular 'person', 'people'
# i... |
require 'rails_helper'
RSpec.describe DocumentTypeConstraint, type: :routing do
describe "#match?" do
let(:request) { double("request") }
before :each do
allow_any_instance_of(described_class).to receive(:load_document_types).and_return(["publication", "news_article", "speech"])
end
context "... |
RSpec.describe Dabooks::Formatter do
subject { described_class.new(transaction_set) }
let(:transaction_set) do
instance_double(Dabooks::TransactionSet, transactions: [t1, t2])
end
let(:t1) do
instance_double(Dabooks::Transaction,
date: Date.new(2018, 12, 11),
description: 'early',
entr... |
FactoryGirl.define do
factory :batch do
name {Faker::Name.name }
start_date { Faker::Date.between(6.days.ago, Date.today) } # Random date between dates
end_date { Faker::Date.between(2.days.ago, Date.today) } # Random date between dates
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.