text stringlengths 10 2.61M |
|---|
Facter.add("php_rpm_version") do
setcode do
Facter::Util::Resolution.exec("/bin/rpm -qa --queryformat '%{VERSION}-%{RELEASE}' php")
end
end
|
require "generators/active_snapshot/migration_generator"
module ActiveSnapshot
class InstallGenerator < MigrationGenerator
source_root File.expand_path("templates", __dir__)
desc "Generates a migration to add a the `snapshots` and `snapshot_items` tables"
def create_migration_file
add_migration(... |
class CreateVisits < ActiveRecord::Migration[5.1]
def change
create_table :visits do |t|
t.string :sitter_id, null: false, index: true
t.integer :price, null: false
t.integer :distance, null: false
t.integer :max_occurences, null: false
t.string :times_avail, null: false, array: true... |
# == Schema Information
#
# Table name: payment_transactions
#
# id :integer not null, primary key
# charge_id :string(255)
# amount :integer
# currency :string(255)
# stripe_customer_id :string(255)
# stripe_token :string(255)
# stripe_token_type :s... |
class Photo < ActiveRecord::Base
belongs_to :user
has_many :comments,
dependent: :destroy
has_many :likes
has_attached_file :image,
:styles => { :medium => "300x300>",
:thumb => "100x100>" }
validates_attachment_content_type :image, { content_type: ["image/jpeg",
"image/gif", "image/png"] }
def build_... |
require 'spec_helper'
# Stub out things referred to in the tests
module Base64
end
module ActiveRecord
class Base
end
end
describe SLG::Meta::TracedMethod do
def trace(method_identifier)
SLG::Meta::TracedMethod.for(method_identifier)
end
subject { trace('String#size') }
describe "parsing method iden... |
module PreachmentRepository
extend ActiveSupport::Concern
include ApplicationRepository
included do
scope :where_date, -> (date) { joins(:info).where('preachment_infos.date = ?', date) }
scope :sorted, -> { joins(:info).order('preachment_infos.date DESC') }
scope :web, -> { sorted.published }
end
en... |
module CronSpec
##
# Base class for parsed cron values.
#
class CronValueBase
attr_reader :lower_limit, :upper_limit
##
# Constructs a new CronValueBase with the upper and lower limits of
# values allowed for this CronValue. For example, when definiting a
# CronValue for a 'minute', the ... |
module ApplicationHelper
def title
base_title = "Residency Ranker"
if @title.nil?
base_title
else
"#{base_title} | #{@title}"
end
end
def logo
image_tag("logo.png", :alt => "Residency Ranker", :class => "round")
end
def new_child_fields_template(form_builder, association, ... |
require 'rails_helper'
describe User do
before do
@user = FactoryBot.build(:user)
end
describe 'ユーザー新規登録' do
context '新規登録がうまくいくとき' do
it "nickname、email、password、password_confirmation、last_name、first_name,last_name_kana、first_name_kana、birthdayが存在すればOK" do
expect(@user).to be_valid
... |
class DropWalletCol < ActiveRecord::Migration[5.2]
def change
remove_column :wallets, :wallet_address
remove_column :wallets, :total_value
end
end
|
require 'test_helper'
class GuillesControllerTest < ActionController::TestCase
setup do
@guille = guilles(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:guilles)
end
test "should get new" do
get :new
assert_response :success
end
... |
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :authenticate_user!
# コントローラーの先頭に記載することで、
# そこで行われる処理はログインユーザーによってのみ実行可能となります。
# 下記の通り記載した場合、記事の一覧、
# 詳細を確認することができるのはログインユーザーのみとなります。
before_action :configure_permitted_parameters, if: :devise_contro... |
require 'rails_helper'
RSpec.describe Loan, type: :model do
describe "Loan validations" do
it {should have_many(:payments)}
it "validate outstanding balance" do
loan = FactoryGirl.create(:loan)
expect(loan.outstanding_balance).to eq(loan.funded_amount)
end
it "testing outstanding balanc... |
require 'test_helper'
class CassandraObject::AttributeMethods::TypecastingTest < CassandraObject::TestCase
class CustomType
end
class CustomCoder < CassandraObject::Types::BaseType
end
class TestIssue < CassandraObject::BaseSchemaless
self.column_family = 'Issues'
attribute :custom_column, type: C... |
require 'rails_helper'
RSpec.feature 'User Registrations', type: :system do
scenario 'Successful registration' do
visit root_path
within 'form#new_user' do
fill_in 'Email', with: 'jon@got.com'
fill_in 'Password', with: 'abc1234'
fill_in 'Password confirmation', with: 'abc1234'
click... |
class TaskInstance < ActiveRecord::Base
belongs_to :task_model
# validates :id, presence: true, uniqueness: true
# validates :task_model_id, presence: true
scope :completed, -> { where('completed_at IS NOT NULL') }
scope :scheduled, -> { where('starts_at IS NOT NULL') }
end
|
class Speaker < ActiveRecord::Base
include Gravatar
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,
:confirmable
belongs_to :company, counter_cache: true
has_many :events
validates :name, presence: true
scope :confirmed, -> { wher... |
# frozen_string_literal: true
require 'json-schema'
module Avia
class ConfigValidator
attr_reader :error
def initialize(config: {}, gds_id: nil)
@config = config
@gds_id = gds_id
@error = ''
create_formats
end
def validate?
response = JSON::Validator.fully_validate(m... |
class Permissions
ALL = [
{
scope: 'campaigns',
label: 'Campaigns/index',
rights: ['none', 'read']
},
{
scope: 'campaign',
label: 'Campaigns/show',
rights: ['none', 'read', 'write']
},
{
scope: 'weekly_reports',
label: 'Weekly reports/index',
... |
# From http://lojic.com/blog/2008/09/04/how-to-write-a-spelling-corrector-in-ruby/
# Copyright (c) Brian Adkins.
def words(text)
text.downcase.scan(/[a-z]+/)
end
def train(features)
model = Hash.new(1)
features.each {|f| model[f] += 1 }
return model
end
LETTERS = ("a".."z").to_a.join
def edits1(word)
n = ... |
#having everything be class methods feels odd right now
#but it may make sense when running them concurrently
#find/replace the output of the verbose stuff to reroute it
# didn't know how to variabalize after 20m work
class Crawler
require 'open-uri'
MAX_PAGES_PER_SITE = 15
def self.crawl_master(suppliers)
... |
require 'csv'
class FilemakerDataImport
# or equals assignment makes debugging this much easier!
LOCATIONS_MEMO ||= {}
STORIES_MEMO ||= {}
STORY_CATEGORIES_MEMO ||= {}
PLACES_MEMO ||= {}
PLACE_CATEGORIES_MEMO ||= {}
URLS_MEMO ||= {}
URL_STORY_ASSIGNMENTS_MEMO ||= {}
URL_PLACE_ASSIGNMENTS_MEMO ||= {}
... |
require 'rails_helper'
RSpec.describe HomeBuy, type: :model do
describe '商品購入' do
before do
@home_buy = FactoryBot.build(:home_buy)
end
context "商品が購入できる時" do
it "address, city_id, number, municipality, streetがあれば購入OK" do
expect(@home_buy).to be_valid
end
it "buildingが空でも購... |
require_relative 'command.rb'
class AskForUrlCommand < Command
def exec
print_message @bot, @chat_id, "Please, specify the URL of content for gif"
end
end
|
class CreateConstituents < ActiveRecord::Migration
def change
create_table :constituents do |t|
t.date :added
t.date :removed
t.string :sym
t.string :name
t.string :cik
t.timestamps null: false
end
end
end
|
# 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... |
# frozen_string_literal: true
class PostsController < ApplicationController
def show
@post = Post.includes(:message, image: { file_attachment: :blob }).find_by(id: params[:id])
redirect_to root_url if @post.nil?
end
end
|
require 'rails_helper'
describe "authentication for put requests", type: :request do
let!(:user) { FactoryGirl.create(:user) }
let!(:business) { FactoryGirl.create(:business) }
it 'returns status code 200 for an authenticated user and a put request' do
put "/businesses/#{business.id}", params: { token: use... |
json.result do
json.messages "ok"
json.rstatus "1"
json.errorcode ""
end
json.data do
json.number @number
json.winners do
if @winners.present?
json.array! @winners.each do |winner|
json.id winner.user.id
json.name winner.user.full_name
json.email winner.user.email
if winn... |
include ActionDispatch::TestProcess
FactoryGirl.define do
factory :user do
sequence(:email) { |n| "uzver#{n}@gmail.com"}
password '123456'
password_confirmation '123456'
end
factory :author do
name Faker::Book.author.gsub(/\W/, '')
end
factory :group do
name Faker::Book.genre.gsub(/\W/,... |
class PasswordResetsController < ApplicationController
def new
end
def create
user = User.find_by_email(params[:email])
if user
user.send_password_reset
redirect_to root_url, flash: {success: "An email has been sent with password reset instructions." }
else
redirect_to signup_url, flash: ... |
module Concerns::Mailmagazine::Association
extend ActiveSupport::Concern
included do
belongs_to :section
has_many :sent_mailmagazines, -> {order("id DESC")}, dependent: :destroy
end
end
|
class CreateCards < ActiveRecord::Migration[5.2]
def change
create_table :cards do |t|
t.string :name
t.integer :card_number
t.string :expiry
t.integer :cv
end
end
end
|
require 'spec_helper'
describe Categorization do
let(:invalid_ids) {['', nil, "abc", "12abc34", "ab123cd", -100, 0]}
it {should have_valid(:category_id).when(1)}
it {should_not have_valid(:category_id).when(*invalid_ids)}
it {should have_valid(:entry_id).when(1)}
it {should_not have_valid(:entry_id).when(*in... |
describe 'Add text and replace multiple matching words by a comma separated list of chars' do
before(:all) {
@text = "Replace%20it%20by%20dashes"
@replaced = "-,*"
}
let(:replace_text){ get "?text=#{@text}&add=replace,dashes&fill_char=#{@replaced}" }
it 'Returns an error msg' do
replace_text
e... |
require 'spec_helper'
describe Lumberjack do
describe "context" do
it "should create a context with tags for a block" do
Lumberjack.context do
Lumberjack.tag(foo: "bar")
expect(Lumberjack.context[:foo]).to eq "bar"
end
end
it "should always return a context" do
context... |
require_relative 'test_helper'
# Internal: The test for Plaid::Identity.
class PlaidIdentityTest < PlaidTest
def test_get
create_item initial_products: [:identity]
response = client.identity.get(access_token)
refute_empty(response.identity)
end
def test_get_invalid_access_token
assert_raises(Pl... |
# frozen_string_literal: true
module Vedeu
module EscapeSequences
# Provides colour related escape sequences.
#
# @api private
#
module Colours
include Vedeu::Common
extend self
# Produces the background named colour escape sequence hash from
# the foreground escape se... |
class Character < ApplicationRecord
belongs_to :period, inverse_of: :characters
validates :name, presence: true,
length: { minimum: 5 }
validates :body, presence: true,
length: { minimum: 5 }
end
|
class Brewery < ActiveRecord::Base
attr_accessible :address, :city, :country, :name, :state, :website
has_many :beers
validates :name, presence: true
def place
if city.present? && state.present? && country.present?
return "#{city}, #{state}, #{country}"
elsif city.present? && state.presen... |
# 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 rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel... |
require 'rails_helper'
RSpec.describe User, type: :model do
before do
@user = User.create(first_name: "Kate", last_name: "Russell")
end
subject { @user }
it "should return first and last" do
expect(@user.first_name).to eq "Kate"
expect(@user.last_name).to eq "Russell"
en... |
class ApplicationController < ActionController::Base
before_action :authorize
protected
def authorize
unless User.find_by(id: session[:user_id])
redirect_to login_url, notice: "Please log in"
end
end
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session i... |
class Project < ApplicationRecord
has_many :team_projects
has_many :teams, through: :team_projects
has_many :surveys, through: :team_projects
belongs_to :course
end
|
# Git Pivotal Tracker Integration
# Copyright (c) 2013 the original author or authors.
#
# 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
#
# ... |
class ApplicationController < ActionController::Base
protect_from_forgery
helper ApplicationHelper
helper_method :current_user, :current_issue
private
def current_user
@current_user ||= Person.find(cookies.signed[:person_id]) if cookies.signed[:person_id]
end
def current_issue
Issue.latest_pub... |
class AddDirStrRefToFileStr < ActiveRecord::Migration[5.1]
def change
add_reference :file_strs, :dir_str, foreign_key: true
end
end
|
# def reverse_words!(message)
# reverse_characters!(message, 0, message.length - 1)
# current_word_start_index = 0
# (0..message.length).each do |i|
# next unless i == message.length || message[i] == ' '
# reverse_characters!(message, current_word_start_index, i - 1)
# current_word_start_index = i + 1... |
class RemoveVotingFromGeoNotes < ActiveRecord::Migration[5.0]
def change
remove_column :geo_notes, :upvotes, :int
remove_column :geo_notes, :downvotes, :int
end
end
|
class Api::CompaniesController < ApplicationController
inherit_resources
defaults class_name: 'Company'
respond_to :json
def permitted_params
params.permit(company: [:name, :address, :city, :country, :email, :phone])
end
end
|
module MinimedRF
module PumpEvents
# Got this from @bewest's decocare
# https://github.com/bewest/decoding-carelink
class JournalEntryMealMarker < Base
def self.event_type_code
0x40
end
def bytesize
9
end
def timestamp
parse_date(2)
end
... |
class Shop < ActiveRecord::Base
has_many :purchase_lists, dependent: :destroy
validates_presence_of :name, :kana, :tel
validates_uniqueness_of :name, :kana
# tel -> 半角数字とハイフンのみ, [4444-22-4444, for 固定] )
validates :tel, format: { with: /(\A\d{4}-\d{2}-\d{4})+\z/i }
# true or falseを指定
validates :i... |
require 'spec_helper'
describe ShowMorePresenter do
let(:blacklight_helper) {
double(blacklight_config: double(index_fields: {}) )
}
subject { ShowMorePresenter.new('', blacklight_helper) }
describe '#render_index_field_value' do
let(:desc_field) { 'desc_metadata__description_tesim' }
context 'i... |
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe GameEngineJob, type: :job do
include(CacheHelper)
let!(:player_left) { create(:user, status: 'online') }
let!(:player_right) { create(:user, status: 'online') }
let!(:game) { create(:game, player_left: player_left, player_right: player_right,... |
# Chapter 3: Letters
puts 'Hello, world!';
puts '';
puts 'Good-bye.';
puts '';
# 3.1 String Arithmetic
puts 'I like ' + 'apple pie.'; # String concatenation
puts 'I like' + ' apple pie.';
puts 'blink ' * 4; # String multiplication
puts 'moo' * 3; # Means 'moo' + 'moo' + 'moo'
puts '';
# 3.2 12 vs. '12'
puts 12 + ... |
class TaskSerializer < ActiveModel::Serializer
attributes :id, :todo, :status, :date, :is_completed
def is_completed
object.status.eql?(STATUS[:closed])
end
end
|
require 'test/tem_test_case.rb'
class TemCryptoHashTest < TemTestCase
def test_crypto_hash
garbage1 = (0...8).map { |x| (31 * x * x + 5 * x + 3) % 256 }
garbage2 = (0...11).map { |x| (69 * x * x + 62 * x + 10) % 256 }
hash_size = 20
sec = @tem.assemble { |s|
s.ldwc hash_size * 3
s.ou... |
require 'test_helper'
class EmployeeMastersControllerTest < ActionController::TestCase
setup do
@employee_master = employee_masters(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:employee_masters)
end
test "should get new" do
get :new
... |
require 'cloudformation_mapper/resource'
class CloudformationMapper::Resource::AwsPropertiesS3Policy < CloudformationMapper::Resource
register_type 'AWS::S3::BucketPolicy'
type 'Template'
parameter do
type 'Template'
name :Properties
parameter do
type 'String'
name :Bucket
end
... |
#
# Cookbook Name:: JobQueue
# Recipe:: default
#
require 'etc'
if ['solo','app_master'].include?(node[:instance_role])
# Install the JobQueue monit file.
run_for_app('cocodot') do
ey_cloud_report "JobQueue" do
message "Installing Monit Email Alerts"
end
template '/etc/monit.d/email_alerts.m... |
class RenameConfigurationIdToSettingIdInExperiments < ActiveRecord::Migration[5.1]
def change
rename_column :experiments, :configuration_id, :setting_id
end
end
|
class RenameGroupOwnerToOwnedBy < ActiveRecord::Migration[5.0]
def change
rename_column :groups, :owner, :owned_by
end
end
|
require './test/support'
module SalesEngine
class InvoiceTest < MiniTest::Unit::TestCase
def setup
contents = CSV.open './test/test_data/invoices_sample.csv', headers: true, header_converters: :symbol
@invoices = Invoice.build_invoice(contents)
end
def teardown
Invoice.clear
end
... |
module Kickstarter
module Pledges
class BuildNoRewardPledgeWithPledgeDailyReportsJob < ApplicationJob
def perform(campaign_id)
campaign = Campaign.find(campaign_id)
BuildNoRewardPledgeWithPledgeDailyReportsService.new(campaign).call
end
end
end
end
|
class Office < ApplicationRecord
has_many :ad_user_details, dependent: :nullify
has_many :ad_users, :through => :ad_user_details
def values_to_s
self.as_json.values.join(", ")
end
def display_office_info
values_to_s
end
end
|
class AddUrlNametoRegions < ActiveRecord::Migration
def change
add_column :regions, :url_name, :string
end
end
|
class CreateMatches < ActiveRecord::Migration
def change
create_table :matches do |t|
t.string :team_one
t.string :team_two
t.boolean :cpu_game
t.integer :player_one_id
t.integer :player_two_id
t.integer :player_one_score
t.integer :player_two_score
t.boolean :is_ti... |
class CreateOrderDetails < ActiveRecord::Migration[5.2]
def change
create_table :order_details do |t|
t.integer :order_detail_id
t.integer :order_id
t.integer :item_id
t.integer :price
t.integer :amount
t.integer :making_status
t.timestamp :created_at
t.timestamp :u... |
require 'spec_helper'
describe AccessToken do
let(:expires_at) { nil }
let(:token) { FactoryGirl.build :access_token, expires_at: expires_at }
# factory
it { should have_a_valid_factory }
# associations
it { should belong_to(:email_address) }
# indexes
it { should have_db_index(:token_digest).u... |
class Follow < ActiveRecord::Base
# リレーションの設定
belongs_to :follower_user,
:foreign_key => "follower_id",
:class_name => "User"
belongs_to :following_user,
:foreign_key => "following_id",
:class_name => "User"
end
|
module ActiveRecord
class Store
DB_NAME = 'test_db'
MODEL_RESOURCE_NAME = 'data_model'
def self.context
@context ||= begin
store_url = NSURL.fileURLWithPath(File.join(NSHomeDirectory(), 'Documents', "#{DB_NAME}.sqlite"))
model_url = NSBundle.mainBundle.URLForResource(MODEL_RESOU... |
require 'rails/generators/rails/scaffold_controller/scaffold_controller_generator'
class Rails::SusanooControllerGenerator < Rails::Generators::ScaffoldControllerGenerator
source_root File.expand_path('../templates', __FILE__)
def create_concerns_file
template 'concerns/controller.rb', File.join('app/controll... |
class AddEnergyTracking < ActiveRecord::Migration
def self.up
create_table :energy_consumptions, :force => true do |t|
t.column :project_id, :integer
t.column :name, :string
t.column :amee_profile_item_id, :string
t.column :energy_consumption_type, :s... |
class City < ApplicationRecord
belongs_to :nation
end
|
module VCAP
module Services
module Mysql
module WithoutWarden
end
end
end
end
module VCAP::Services::Mysql::WithoutWarden
def mysqlProvisionedService
VCAP::Services::Mysql::Node::ProvisionedService
end
def pre_send_announcement_internal(options)
@pool_mutex = Mutex.new
@pools... |
class UsersController < ApplicationController
before_action :set_user, only: [:show, :edit, :update, :destroy]
before_action :check_login, only: [:show, :edit, :update, :logout]
def index
@user = User.find_by(id: session[:user])
end
def new
@user = User.new()
end
def create... |
require 'amazon-drs/base'
module AmazonDrs
class Error < Base
attr_accessor :message, :error_description, :error
def parse_body(body)
json = JSON.parse(body)
@message = json['message'] if json['message']
@error = json['error'] if json['error']
@error_description = json['error_descrip... |
require 'rails_helper'
RSpec.describe "stus/new", type: :view do
before(:each) do
assign(:stu, Stu.new(
:name => "MyString",
:address => "MyString",
:syndrome_id => 1
))
end
it "renders new stu form" do
render
assert_select "form[action=?][method=?]", stus_path, "post" do
... |
class UsersController < ApplicationController
load_and_authorize_resource only: [:index]
#before_filter :authenticate_user!, only: [:index, :edit, :update]
def index
@users = current_company.users.all
respond_to do |format|
format.js
end
end
def show
@user = User.find(params[:id])
... |
class Badge < ActiveRecord::Base
has_many :badgings
def self.find_or_create_by_name(name)
Badge.where(:name => name).first || create(:name => name)
end
def icon
if read_attribute(:icon)
read_attribute(:icon)
else
"/images/#{name.parameterize}.jpg"
end
end
end
|
require 'addressable/uri'
require 'digest/md5'
require 'net/https'
require 'thread'
require 'timeout'
require 'yaml'
require 'zlib'
require 'planet/log'
module Planet
# map a URI to a readable and (relatively) unique filename
def Planet.filename uri
name = uri_norm(uri)
name.sub!(/^\w+:\/*(\w+:|www\.)?/,... |
class OpenWeatherMap
include HTTParty
@api_key = ENV["OPEN_WEATHER_MAP_KEY"]
base_uri "https://api.openweathermap.org/data/2.5/weather?APPID=#{@api_key}&units=imperial"
def conditions_for(zipcode)
loc = OpenWeatherMap.get_loc_by_zip(zipcode)
if loc
self.class.get("&id=#{loc}")
else
sel... |
class FixUserAgain < ActiveRecord::Migration
def change
remove_column :users, :users_admin
add_column :users, :users_admin, :boolean, default: false
end
end
|
class CreateDepositors < ActiveRecord::Migration
def change
create_table :depositors do |t|
t.string :name, null: false
t.string :basic_authentication_user_id, null: false
t.string :password_digest, null: false
t.timestamps null: false
end
add_index :depositors, :name, unique: tru... |
class MessagesController < ApplicationController
def new
@message = Message.new
@team_id = params[:id]
@team = Team.find_by(id: params[:id])
@team_entries = @team.team_entries
@messages = @team.messages
end
def create
if TeamEntry.where(:user_id => current_user.id, :team_id => params[:... |
class ChangePublishedShouldNotNil < ActiveRecord::Migration[4.2]
def change
begin
Newsitem.where(:published => nil).update_all(:published => DateTime.now)
rescue
# pass
end
execute "ALTER TABLE newsitems ALTER COLUMN published SET DEFAULT now()"
execute "ALTER TABLE newsitems ALTER COL... |
require 'test_helper'
class RushClassesControllerTest < ActionController::TestCase
setup do
@rush_class = rush_classes(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:rush_classes)
end
test "should get new" do
get :new
assert_response... |
class FontBigShouldersText < Formula
head "https://github.com/google/fonts/raw/main/ofl/bigshoulderstext/BigShouldersText%5Bwght%5D.ttf", verified: "github.com/google/fonts/"
desc "Big Shoulders Text"
homepage "https://fonts.google.com/specimen/Big+Shoulders+Text"
def install
(share/"fonts").install "BigSho... |
module ApiMonkey::Filterable
extend ActiveSupport::Concern
included do
define_singleton_method :filter do |filtering_params|
results = self.where(nil)
return results unless filtering_params
filtering_params.each do |key, value|
results = if key.split('.').count > 1
... |
class Category < ActiveRecord::Base
has_many :categories_products
has_many :products, through: :categories_products
end
|
require 'meal_serving'
load 'ingredient.rb'
load 'ingredient_quantity.rb'
load 'recipe.rb'
describe MealServing do
let(:pomid) {Ingredient.new(name: 'Tomato', cost: 100)}
let(:pomid_quantity) do
[IngredientQuantity.new(ingredient: pomid, quanity: 200),
IngredientQuantity.new(ingredient: pomid, quanity: 2... |
class AddDataFile2ToProducts < ActiveRecord::Migration
def change
add_column :products, :data_file_2, :string
end
end
|
module CustomErrorHelper
def custom_form_errors(object)
return "" unless errors? object
messages = object.errors.full_messages.map { |msg| content_tag(:li, msg) }.join
count = object.errors.count
html = <<-HTML
<div id="error_explanation" class="alert alert-danger">
<strong>Error(s) : #{co... |
Rails.application.routes.draw do
root to: 'contacts#index'
resources :contacts do
collection { post :sync }
end
end
|
require 'rspec/core/formatters'
module Rspec
module Rotten
module Formatters
class InitialReportFormatter
RSpec::Core::Formatters.register self, :example_passed, :example_failed, :example_pending, :close
def initialize(output)
@output = output
@arr = []
end
... |
module ReceiptPrinterHelper
include ApplicationHelper
def get_stylesheet_for_current_receipt_template
stylesheets=[]
stylesheets<<"_receipt_templates/receipt_global"
if rtl?
stylesheets<<receipt_path+'/rtl/_template_'+template_name
else
stylesheets<<receipt_path+'/_template_'+template... |
module Api::V1
class SessionsController < ApplicationController
skip_before_action :authenticate
def new
end
def create
params[:email].strip!
params[:email].downcase!
user = User.find_by(email: params[:email])
if user
if user.authenticate(params[:password])
... |
class FormsController < ApplicationController
def index
@user = User.find(session[:user]["id"])
@forms = @user.forms
end
def new
@form = Form.new
end
def create
@user = User.find(session[:user]["id"])
@form = @user.forms.create!(form_params)
redirect_to new_form_question_path(@for... |
class FontNotoSansGeorgian < Formula
head "https://noto-website-2.storage.googleapis.com/pkgs/NotoSansGeorgian-unhinted.zip", verified: "noto-website-2.storage.googleapis.com/"
desc "Noto Sans Georgian"
homepage "https://www.google.com/get/noto/#sans-geor"
def install
(share/"fonts").install "NotoSansGeorgi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.