text stringlengths 10 2.61M |
|---|
Rails.application.routes.draw do
devise_for :users
root to: "books#index"
get "/my_favorites", :controller => "books", :action => "my_favorites"
get "/users", :controller => "users", :action => "index"
get "/users/:id", :controller => "users", :action => "show"
# Routes for the Classification resource:
... |
#!/usr/bin/env ruby
require 'csv'
require 'slop'
require 'ruby-progressbar'
def row_count(infile)
`wc -l #{infile}`.chomp.strip.split(' ').first.to_i
end
def export(opts = {})
pb = ProgressBar.create(title: 'Rows', total: row_count(opts[:in]), format: '%e |%b>>%i| %p%% %t')
count = 0
total = 0
CSV.open(op... |
Rails.application.routes.draw do
mount RailsAdmin::Engine => '/admin', as: 'rails_admin'
get 'home/index'
devise_for :users
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
root 'home#index'
resources :subscription, only: [:index, :show, :new, :create]
... |
#!/usr/bin/env ruby
# -*- coding: UTF-8 -*-
#=============================================================================
# FileName: string.rb
# Desc:
# Author: Lolly
# Email: cclolly@gmail.com
# HomePage:
# Version: 0.0.1
# LastChange: 2014-02-24 01:41:50
# History:
#=======... |
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
Rails.application.routes.draw do
# devise_for :users
devise_for :users, controllers: { registrations: "registrations" }
authenticated :user do
root 'recipes#index', as: :authenticated_root
end
root to: ... |
Qiankun::Admin.controllers :activities do
get :index do
@title = "Activities"
@activities = Activity.all
render 'activities/index'
end
get :new do
@title = pat(:new_title, :model => 'activity')
@activity = Activity.new
render 'activities/new'
end
post :create do
@activity = Activ... |
class Product < ActiveRecord::Base
monetize :price_cents, numericality: true
mount_uploader :image, ProductImageUploader
has_many :reviews
belongs_to :category
validates :name, presence: true
validates :price_cents, presence: true, numericality: true
validates :quantity, presence: true, numericality: t... |
# frozen_string_literal: true
class Types::Location::PrayerType < Types::BaseObject
include Rails.application.routes.url_helpers
field :id, ID, null: false
field :name, String, null: false
field :snippet, String, null: false
field :content, String, null: true
field :location, Types::LocationType, null: fa... |
#!/usr/bin/env ruby
require 'vagrant'
module VagrantHosts
class HostManager
attr_accessor :hostname, :ip, :ghost
def initialize(hostname, ip, ghost=Host)
self.hostname = hostname
self.ip = ip
self.ghost = ghost
end
def add_host_entry
self.ghost.add(hostname, ip)
e... |
class User < ApplicationRecord
# 유저는 여러개의 글을 가질 수 있다. (user.rb)
# 글은 유저 1명을 가질 수 있다.
has_many :posts # posts 여야만 함!
end
|
class DelayedEmployeeLeaveCredit < Struct.new(:parameters, :leave_credit_id, :leave_type_ids)
# Manual credit
def perform
emp_ids = JSON.parse(parameters)
@employees = Employee.find(:all , :conditions => ["id IN (?)",emp_ids], :include => {:leave_group => :leave_group_leave_types})
employee_leave... |
require 'spec_helper'
describe "photos/index" do
before(:each) do
assign(:photos, [
stub_model(Photo,
:user => nil,
:latitude => 1.6,
:longitude => 1.5
),
stub_model(Photo,
:user => nil,
:latitude => 1.6,
:longitude => 1.5
)
])
end
... |
class CreateRequests < ActiveRecord::Migration
def change
create_table :requests do |t|
t.references :passenger, index: true, foreign_key: true
t.string :distini
t.string :distfin
t.integer :monto
t.string :direcexini
t.string :directexfin
t.integer :pasajeros
t.str... |
require 'rails_helper'
feature 'As a logged in user' do # rubocop:disable Metrics/BlockLength
context 'when visiting /dashboard' do
it 'sees all followed users' do
VCR.use_cassette('github_current_users_repos',
allow_playback_repeats: true) do
VCR.use_cassette('github_current... |
class DeleteProfiles < ActiveRecord::Migration[5.0]
def up
drop_table :profiles
end
end
|
require 'rdf'
module RDFVocabularies
class DCTERMS < RDF::Vocabulary("http://purl.org/dc/terms/")
property :format
end
end
|
require 'spec_helper'
describe Company do
subject { build :company }
it { should be_valid }
it { should have_many(:passports) }
it { should validate_presence_of(:name) }
it { should validate_presence_of(:city) }
it { should validate_presence_of(:address) }
it { should_not validate_presence_of(:email... |
class ProductPicture < ApplicationRecord
belongs_to :picture, dependent: :destroy
belongs_to :product
end
|
# frozen_string_literal: true
resource_name :elasticsearch_request
METHOD_VARIANTS = %w[get post put delete]
.flat_map { |element| [element, element.upcase] }
.flat_map { |element| [element, element.to_sym] }
.freeze
DEFAULT_TIMEOUT = 8
self.class.include ::Ayte::Chef::Cookbook::ElasticSearch::ResourceDefiniti... |
# encoding: utf-8
FactoryGirl.define do
factory :event do
user { |c| c.association(:user) }
region { |c| c.association(:region) }
title "这个是一个活动"
description "这个是活动的内容"
address "上海市内茶陵北路20号"
begin_at (Time.parse '2014-12-10') + 10.days
end_at (Time.parse '2014-12-10') + 20.days
block... |
require_relative '../helpers/palindromes'
class OEIS
A060948_SEQUENCE = IntrinsicKPalindromes.new(11, 1000).all
def self.a060948(n)
raise "A060948 is not defined for n = #{n} < 1" if n < 1
A060948_SEQUENCE[n - 1]
end
end
|
# encoding: utf-8
class Agenda < ActiveRecord::Base
belongs_to :voluntario
scope :por_tipo, lambda { |tipo| where('tipo = ?', tipo) }
scope :por_data, lambda { |data| where('data = ?', data) }
attr_accessor :data_formatada
validates :data, :presence => true
validates :voluntario, :presence => true
... |
# Integrates backgroundDRb rails plugin (http://backgroundrb.rubyforge.org/) with upload to cut out long running processes in rails request invocation loop.
# Configure your model to process it's versions in backgroundDRb job by setting :backgroundrb option to true.
# uploadify :conversions => {:thumb => 50}, :backg... |
module AchievementConcerns
module LearningTrackAchievementable
extend ActiveSupport::Concern
include AchievementConcerns::SimpleAchievementable
included do
after_update :publish_learning_track
end
private
def create_learning_track
unless self.parent.nil?
grant_on_create :... |
class Tag < ActiveRecord::Base
has_and_belongs_to_many :links, counter_cache: true
def inspect
"<#{name} (#{links_count})>"
end
end
|
require 'utils/value_stringifier'
module ActiveFlags
class Flag < ApplicationRecord
belongs_to :subject, polymorphic: true
validates :subject, :key, :value, presence: true
validates :key, uniqueness: { scope: :subject }
after_save :notify_subject_flag_has_changed, if: proc { |flag| flag.saved_chang... |
class User < ActiveRecord::Base
attr_accessible :username, :password, :password_confirmation, :first_name, :last_name, :email
has_secure_password
validates :username, presence: true
validates :first_name, presence: true
validates :last_name, presence: true
end
|
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :set_language
def set_language
if session[:locale]
I18n.locale = session[:locale]
else
if current_admin
I18n.locale = current_admin.locale
elsif current_user
I18n.locale = current_use... |
class ArtistsController < ApplicationController
before_action :authenticate_user!
def index
@artists = Artist.order(:name)
end
def new
@artist = Artist.new
@modalities = Modality.all
@institutions = Institution.all
end
def show
@artist = Artist.find(params[:id])
end
def edit
... |
class MuralsController < ApplicationController
before_action :authenticate_user!, except: [:index, :show]
def new
@mural = Mural.new
@rating_collection = [
[1, "1"],
[2, "2"],
[3, "3"],
[4, "4"],
[5, "5"]
]
end
def create
@mural = Mural.new(mural_params)
@mu... |
VOWELS = ["a", "e", "i", "o", "u", "y"]
DICTIONARY = "/usr/share/dict/words" #can
class Tree
def initialize
@root = {}
('a'..'z').each do |letter|
@root[letter] = TreeNode.new(letter)
end
end
def build_the_tree
IO.foreach(DICTIONARY) do |w|
w = w.strip.downcase
self.push_ont... |
require 'gds_api/content_store'
require 'gds_api/rummager'
module Services
DOCUMENT_FORMATS_YAML = "https://raw.githubusercontent.com/alphagov/rummager/master/config/govuk_index/migrated_formats.yaml".freeze
def self.content_store
@content_store ||= GdsApi::ContentStore.new(Plek.new.find("content-store"))
e... |
class AddColumnsToUser < ActiveRecord::Migration
def change
add_column :users, :twitter_oauth_token, :string
add_column :users, :twitter_oauth_secret, :string
add_column :users, :twitter_permissions, :hstore
add_column :users, :twitter_connection, :boolean, default: false
add_column :users, :twitt... |
class CommentObserver < ActiveRecord::Observer
def after_save(comment)
comment.post.increment!(:rating, Comment::COMMENT_RATE)
end
def after_destroy(comment)
comment.post.decrement!(:rating, Comment::COMMENT_RATE)
end
end
|
require_relative "helper"
require_relative "../lib/blind/world"
require_relative "../lib/blind/point"
describe Blind::World do
let(:world) { Blind::World.new(5) }
let(:minefield_range) do
-Blind::World::MINE_FIELD_RANGE.max .. Blind::World::MINE_FIELD_RANGE.max
end
it "must have mine positions" do
w... |
class Map < ActiveRecord::Base
def url
'http://wiki.teamliquid.net/starcraft2/index.php?title=Special%3ASearch&search=' + URI.escape( name ) + '&go=Go'
end
end
|
#A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
#a^2 + b^2 = c^2
#For example, 32 + 42 = 9 + 16 = 25 = 52.
#There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc.
require "./util"
include Util
n = 1000
time("Problem 9 ==>") do
a = (1..n/2).to_... |
require 'json'
require 'net/http'
require 'net/http/digest_auth'
require 'open-uri'
require 'uri'
module CloudappExport
class Api
DEFAULT_HOST = "my.cl.ly"
def initialize(options = {})
@options = options
end
def authenticate!
response = request("items?per_page=1")
return true if r... |
# == Schema Information
#
# Table name: special_prices
#
# id :integer not null, primary key
# start :datetime
# stop :datetime
# price :integer
# is_sale :boolean
# product_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
FactoryG... |
# frozen_string_literal: true
module NCMB
class Increment
include NCMB
def initialize(amount = 1)
@amount = amount
end
def to_json(a)
"{\"__op\": \"Increment\", \"amount\": #{@amount}}"
end
def amount
@amount
end
end
end |
class Customer < ApplicationRecord
require 'roo'
after_create :send_message
validates :name , presence:true
validates :membership_number, presence:true
validates :contact_number, presence: true
def send_message
require "rubygems"
require "net/https"
require "uri"
require "json"
uname ... |
class User < ActiveRecord::Base
set_table_name "#{table_name_prefix}users#{table_name_suffix}"
# Account statuses
STATUS_ANONYMOUS = 0
STATUS_ACTIVE = 1
STATUS_REGISTERED = 2
STATUS_LOCKED = 3
USER_FORMATS = {
:firstname_lastname => '#{firstname} #{lastname}',
:firstname => '#{firstn... |
class Course < ApplicationRecord
has_many :chapters
has_many :user_courses
has_many :users, through: :user_courses
has_many :quiz_questions
has_many :quiz_answers, through: :quiz_questions
end
|
require 'sqlite3'
#creates database
db = SQLite3::Database.new("birthday_tracker.db")
#creates a table of friends and their birthdays
create_friend_table = <<-SQL
CREATE TABLE IF NOT EXISTS friends(
id INTEGER PRIMARY KEY,
friend_name VARCHAR(255),
age INT,
birth_month INT,
birth_day INT,
l... |
require 'test_helper'
class UserTest < ActiveSupport::TestCase
context "validations" do
should "not allow a first name with numbers" do
user = Fabricate.build(:user, first_name: "foo1")
assert_not user.valid?
end
should "not allow a first name of less than 2 characters" do
user = Fabri... |
=begin
module Shout
def self.yell_angrily(words)
words + "!!!" + " :("
end
def self.yelling_happily
puts "Woooohooo!!!"
end
end
puts Shout.yell_angrily("Let's go")
Shout.yelling_happily
=end
module Calling
def calls(name)
2.times{|t| puts "Came here! #{name}!"}
end
end
... |
class StudentList
attr_reader :students
def initialize
@students = []
end
def add(name)
@students << name
end
def count_students
@students.count
end
def clear_students
@students.clear
end
end
|
#encoding: utf-8
require_relative File::expand_path('./created_at', __dir__)
require 'logger'
module VmstatCat
module AppLogger
extend CreatedAt
def self.get
self::ensure_directory
@@logger = Logger.new(File::expand_path("../log/log_#{created_at}.log", __dir__)) unless defined? @@log... |
module Banker
class Barclays < Base
LOGIN_URL = "https://bank.barclays.co.uk/olb/auth/LoginLink.action"
EXPORT_URL = "https://bank.barclays.co.uk/olb/balances/ExportDataStep1.action"
attr_accessor :accounts, :ofx
FIELD = {
surname: "surname",
membership_number: "membershipNumber",
... |
class TopicsController < ApplicationController
before_action :require_login
before_action :only_see_own_page, only: [:show]
def new
@topic = Topic.new
end
def create
@topic = Topic.new(topic_params)
user = current_user
@topic.user = user
if @topic.save
redirect_to @topic
else
... |
module StrokeDB
module Validations
module Base
include Declarations
def register_validation(validation)
local_declarations(:validations, []) do |list|
list << validation
end
end
def validations
inherited_declarations(:validations) do |inherit... |
'Environment Variables'
control 'PATH variable' do
impact 'high'
title 'PATH should contain ~/.local/bin for nbstripout'
desc 'PATH should contain ~/.local/bin for nbstripout. This is currently broken,' \
'however the fix would be to change the '
tag 'environment'
tag 'nbstripout'
tag 'known_broken'
d... |
class PeptideGenomedbResult < ActiveRecord::Base
belongs_to :bioentries
has_many :spectrum_results
end
|
class ApplicationController < ActionController::Base
protect_from_forgery
helper :layout
before_filter :check_for_current_event, :except => [:sign_in, :sign_out]
def after_sign_in_path_for(resource_or_scope)
if resource_or_scope.is_a?(User)
# if Event.current_event
if resource_or_sco... |
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe OrderPointsJob, type: :job do
describe '#perform' do
it 'enqueues email' do
customer_detail = create(:customer_detail)
ActiveJob::Base.queue_adapter = :test
expect do
OrderPointsJob.perform_now(customer_detail.email)
... |
module Testbeds
class Index
attr_reader :beds
def find_index_file base_path = Pathname.new('.')
path = File.expand_path(base_path.join('Bedfile'))
return path if File.file?(path)
# if we hit root, there is no Bedfile
return nil if path =~ /:\\Bedfile/ or path =~ /^\/Bedfile/
fin... |
class CreateIndoorkadais < ActiveRecord::Migration
def change
create_table :indoorkadais do |t|
t.integer :indoor_id
t.string :wallname
t.string :routename
t.string :grade
t.boolean :newflag, default: true, null: false
t.timestamps null: false
end
end
end
|
require 'minitest/autorun'
require 'minitest/pride'
require './lib/player'
require './lib/message'
class PlayerTest < Minitest::Test
def test_it_exists
p = Player.new
assert p
end
def test_it_starts_with_set_of_grids
assert Player.new.personal_grid
assert Player.new.opponent_grid
end
def te... |
require 'rails_helper'
require 'spec_helper'
RSpec.describe "cars/index", type: :view do
# before(:each) do
# assign(:cars, [
# Car.create!(
# :name => "Name",
# :number => "Number",
# :pts => "Pts",
# :pts_date => "Pts Date"
# ),
# Car.create!(
# :name =... |
#!/usr/bin/env ruby
def passphrase(input)
array = input.split("\n").map{ |row| row.split(' ')}
valid_phrases = 0
array.each do |line|
line.map!{ |word| word.chars.sort.join} # Returns alphabetically sorted words.
valid_phrases += 1 unless line.detect{ |word| line.count(word) > 1 } # Checks for duplicate ... |
module GamesHelper
def opponent(game, team)
if(game.home_team == team)
game.visiting_team.display_name
else
game.home_team.display_name
end
end
def start_time(game)
starts = game.starts_at
starts.strftime('%m/%d/%Y %I:%M')
end
def home_winner(game)
game_score_label("W",... |
class PagesController < ApplicationController
before_action :authenticate_user!, except: [:blog, :show]
before_action ->{ raise CanCan::AccessDenied if !action_name.in?(%w(blog show)) && cannot?(:manage, Page) }
before_action :set_page, only: [:show, :edit, :update, :destroy]
# GET /pages
def index
@pag... |
class Admin::AdminController < ApplicationController
before_action :set_user#, except: [:show]
before_action :require_user#, only: [:show]
before_action :set_view_path
end |
require 'rspec'
require './Liability'
require './Employee'
describe Liability do
let(:liability) { Liability.new(Employee.new('Johnny','Smith', 120000, 28000, 38),100,100) }
it "should expose it's employee instance variable which is an Employee object" do
expect(liability.employee).to be_a(Employee)
end
... |
require 'spec_helper'
#for tests to run sucessfully you need to clone the development database structure to a test database
# bundle exec rake db:test:prepare
describe "User" do
before do
@user = User.new(name: "Example User", email: "user@example.com",
password: "foobar", password_confirmation: "foobar")
... |
require 'javaclass/classpath/composite_classpath'
module JavaClass
module Classpath
# A reference to a Maven artefact. This is a group/artefact/version tuple that points to a single Jar in the Maven repository.
# Author:: Peter Kofler
class MavenArtefact
attr_reader :group, :name, :ver... |
class Game < ApplicationRecord
translates :title, :description, :body
has_many_attached :avatar
has_many :articles
has_many :game_developers
has_many :developers, through: :game_developers
has_many :game_genres
has_many :genres, through: :game_genres
validates_with AvatarValidator
end
|
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
layout 'exposition/application'
helper Exposition::Admin::FlashesHelper
end
|
require 'spec_helper'
describe AngellistApi::Client::Tags,
:vcr => { :cassette_name => 'tags' } do
let(:client) { AngellistApi::Client.new }
it 'gets info for a tag' do
tag = client.get_tag(856)
tag.display_name.should eq 'Venture Capital'
end
it "gets a tag's children" do
children = client.ge... |
#
# Cookbook Name:: wheretosmokeapi
# Recipe:: default
#
# Copyright 2014, M. Shanken Communications
#
# All rights reserved - Do Not Redistribute
#
# Creates log and cache dirs for the Kohana project.
directory "/srv/www/wheretosmokeapi/current/application/logs" do
recursive true
owner "www-data"
group "www-da... |
#!/usr/bin/env ruby
require 'optparse'
require 'fileutils'
def parse_options(options)
OptionParser.new do |opts|
opts.banner = 'Usage: backup.rb [options]'
opts.on('-h', '--help', 'Help') do
puts opts
exit
end
opts.on('-f', '--from source', 'From which folde... |
class RemovePositionRotationTranslationFromPoi < ActiveRecord::Migration
def change
remove_column :poi_datas, :position
remove_column :poi_datas, :rotation
remove_column :poi_datas, :scale
end
end
|
Vagrant.configure(2) do |config|
config.vm.box = "ubuntu/trusty64"
config.vm.box_check_update = false
config.ssh.insert_key = false
config.ssh.forward_agent = true
config.vm.provision "file", source: "~/.gitconfig", destination: ".gitconfig"
config.vm.network "private_network", ip: "11.0.0.30"
# Link the... |
module DataMigrations
class Migration
attr_reader :source, :target, :instructions
def initialize(source, options = {})
@source = Table.new(source)
@target = Table.new(options[:to])
@instructions = []
yield self
end
def run!
instructions.each(&:execute)
end
def... |
class Admin::OrganizationsController < ApplicationController
before_filter :require_admin_login
# GET /admin/organizations
# GET /admin/organizations.json
def index
@admin_organizations = Organization.active
@admin_organization = Organization.new
end
def suspended
@admin_organizations = Organ... |
asset_equal('apple', 'apple')
assert_includes([1, 2, 3, 4, 5], 3)
assert_instance_of(String, 42)
assert_includes(['a', 'b', 'c'], 'd')
assert('apples'=='oranges')
assert_raises(StandardError) do
raise ZeroDivisionError, "Oops!"
end
assert_instance_of(Hash, {})
|
# frozen_string_literal: true
require 'kruger/version'
require 'httparty'
require 'kruger/client'
module Kruger
class Error < StandardError; end
end
|
$LOAD_PATH << File.expand_path(File.dirname(__FILE__) + "/../lib")
require 'money/money'
describe Money do
it "is associated to the singleton instance of VariableExchangeBank by default" do
Money.new(0).bank.object_id.should == Money::VariableExchangeBank.instance.object_id
end
specify "#cents returns the amoun... |
module Calil
class Book
FIND_ENABLE_LIMIT = 100
RETRY_LIMIT = 10
RETRY_WAIT_TIME = 5
module ContinueStatus
CONTINUE = "1"
CLOSE = "0"
end
def self.find(isbns, systemids, params = {})
params.merge!({
isbn: isbns.join(","),
systemid: systemids.join(","),
... |
class CreateEstimates < ActiveRecord::Migration[5.0]
def change
create_table :estimates do |t|
t.string :location, null: false
t.float :distance, null: false
t.float :final_price, null: false
t.string :fence_material, null: false
t.float :fence_height, null: false
t.integer :ga... |
class RemoveObsoleteFieldsFromQlogs < ActiveRecord::Migration
def self.up
remove_column :qlogs, :notice
remove_column :qlogs, :error
remove_column :qlogs, :session
remove_column :qlogs, :targets
remove_column :qlogs, :entry
end
def self.down
add_column :qlogs, :notice, :string... |
$:.unshift File.join(File.dirname(__FILE__),"..","lib")
$:.unshift File.join(File.dirname(__FILE__))
require 'minitest/autorun'
require 'rim/git'
require 'rim/module_info'
require 'rim/rim_info'
require 'rim/status_builder'
require 'rim/sync_helper'
require 'rim/upload_helper'
require 'test_helper'
require 'fileutils'... |
class TagsController < ApplicationController
def index
@title = 'Tags'
@tags = Group.tag_counts( :order => 'name' )
end
def permalink
@title = "Tagged '#{params[:tag]}'"
@groups = Group.find_tagged_with params[:tag]
render :action => 'show'
end
end
|
# === Using asset timestamps
# in order to work caching, all your application servers must
# return the same timestamps for assets. This means that they must have their clocks
# synchronized. If one of them drifts out of sync, you'll see different
# timestamps at random and the cache won't work. In that case the browse... |
class Buyer
class Authenticator
attr_reader :email, :password
def initialize(email:, password:)
@email = email
@password = password
end
def call
user.authenticate(password)
end
private
def user
Buyer.find_by(email: email) || Visitor.new
end
end
end
|
# frozen_string_literal: true
require "spec_helper"
describe LiteCable do
it "has a version number" do
expect(LiteCable::VERSION).not_to be nil
end
end
|
#!/usr/bin/env ruby
file = File.open('./import/load.cypher', 'w')
file.write <<-CYPHER
USING PERIODIC COMMIT
LOAD CSV WITH HEADERS FROM "file:///entities.csv" AS row
FIELDTERMINATOR '|'
CREATE (:Entity { entity_id: toInteger(row.id), name: row.name, blurb: row.blurb, primary_ext: row.primary_ext, created_at: row.crea... |
require_relative '../spec_helper'
require 'rack/test'
require File.expand_path('app/app')
require File.expand_path('app/controllers/speakers')
describe 'SpeakersController' do
include Rack::Test::Methods
def app
Confy::App
end
describe 'on GET to /speakers/:twitter' do
describe 'when twitter is vali... |
require 'multi_json'
require 'airbrake_api'
module AirbrakeCli
module Configuration
extend self
def configured?
File.exist?(datafile)
end
def configure_api_client!
raise 'not yet configured' unless configured?
AirbrakeAPI.configure do |config|
config... |
class Ban < ActiveRecord::Base
validates_presence_of :ip, :reason
end
|
class Area < ApplicationRecord
# Extensions
include Manageable
include ActivityMonitorable
include HasClient
include Location
nilify_blanks
searchable_columns %w[name]
audited except: %i[summary_email_sent_at summary_metadata]
# Associations
belongs_to :country, foreign_key: :country_code, primar... |
class BulkDiscountsController < ApplicationController
def index
@merchant = Merchant.find(params[:merchant_id])
end
def show
@merchant = Merchant.find(params[:merchant_id])
@discount = @merchant.bulk_discounts.find(params[:id])
end
def new
@merchant = Merchant.find(params[:merchant_id])
... |
# frozen_string_literal: true
require 'bundler/setup'
require 'codacy-coverage'
require 'simplecov-murmur'
SimpleCov.formatters = [
SimpleCov::Formatter::MurMurFormatter,
SimpleCov::Formatter::HTMLFormatter,
Codacy::Formatter
]
SimpleCov::Formatter::MurMurFormatter.mode = :all
SimpleCov.start do
add_filter ... |
require 'spec_helper'
describe Mailbox do
describe "::exists?" do
before(:each) do
BoxMembership.stub(:create).and_return("new membership")
@user1 = double("User")
@user1.stub(:id).and_return(1)
@user1.stub(:username).and_return("user1")
@user2 = double("User")
@user2.stub(:... |
class Cat < ActiveRecord::Base
has_many :cat_rental_requests, dependent: :destroy
COLORS = %w(brown white orange black grey calico)
SEXES = %w(M F)
validates :color, inclusion: { in: COLORS }
validates :sex, inclusion: { in: SEXES }
def age
Time.now.to_date - self.birth_date
end
end
|
class Ingredient < ActiveRecord::Base
has_many :recipe_ingredients
has_many :recipes, through: :recipe_ingredients
has_many :users, through: :recipes
validates_uniqueness_of :name
end
|
# frozen_string_literal: true
module CheckstyleReports
VERSION = "0.1.0"
end
|
require 'net/http'
require 'uri'
require 'json'
module Services
class Payroll < Base
# rubocop:disable Metrics/AbcSize
def call
response = get("clientes/liquidaciones/#{api_key}")
if response.code == '200'
{
result: JSON.parse(response.body)
}
else
{
... |
Spree::Order.class_eval do
scope :total, -> {
where(state: 'complete').where.not(payment_state: nil, shipment_state: nil)
}
scope :unpaid, -> {
where(payment_state: 'balance_due')
}
scope :unshipped, -> {
where(payment_state: 'paid').where.not(shipment_state: 'shipped')
}
scope :success, -> {
... |
class FoodProduct < ActiveRecord::Base
belongs_to :group
has_many :purchase_list, dependent: :destroy
has_many :employees, through: :group
has_one :fes_year, through: :group
validates_presence_of :group_id, :name, :first_day_num, :second_day_num
validates_numericality_of :group_id, :first_day_num, :second_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.