text stringlengths 10 2.61M |
|---|
# Why is this a spec_slow_helper instead of spec_helper
# Because it is extremely slow to load all of the following dependencies:
#
# * SimpleCov
# * EngineCart (and therefore the underlying internal Rails application)
# * Rails
#
# But overtime the slowness grows. See the sibling helpers: ./spec/*_helper.rb
# (i.e. sp... |
# frozen_string_literal: true
class CreateJoinTableUserProduct < ActiveRecord::Migration[5.2]
def change
create_join_table :products, :users, table_name: :users_products do |t|
t.index %i[user_id product_id]
t.boolean :is_paid
end
end
end
|
# frozen_string_literal: true
class GuestAbility < Ability
def initialize
abilities
end
private
def abilities
raise NotImplementedError
end
end
|
class SessionsController < ApplicationController
def add_lesson
lessons.push(lesson).uniq!
render status: :ok, json: lessons.to_a
end
def remove_lesson
lessons.delete(lesson)
render status: :ok, json: lessons.to_a
end
protected
def lessons
session[:lessons] ||= []
end
def lesson
... |
require 'silence'
require 'hq/division'
require 'hq/super_region'
require 'hq/region'
module Entries::HQ
class Bootstrapper
class << self
# Entries::HQ::Bootstrapper.bootstrap!(year: 2015, stage: 'regional', division: 'men')
def bootstrap!(*args)
puts "bootstrapping #{args.inspect}"
... |
# frozen_string_literal: true
module Auths
module Error
class Unauthorized < AuthError
end
end
end
|
class AddFieldsToBrokerInfo < ActiveRecord::Migration
def change
# add_column :broker_infos, :company_name, :string
add_column :broker_infos, :website, :string
add_column :broker_infos, :description, :text
add_column :broker_infos, :email, :string
add_column :broker_infos, :additional_email, :stri... |
# -*- coding: utf-8 -*-
require 'cgi'
module Plugin::Bitly
USER = 'mikutter'.freeze
APIKEY = 'R_70170ccac1099f3ae1818af3fa7bb311'.freeze
SHRINKED_MATCHER = %r[\Ahttp://(bit\.ly|j\.mp)/].freeze
extend self
# bitlyユーザ名を返す
def user
if UserConfig[:bitly_user] == '' or not UserConfig[:bitly_user]
US... |
# == Schema Information
#
# Table name: boroughs
#
# id :integer not null, primary key
# name :string(255) not null
# order :integer default(0)
# created_at :datetime not null
# updated_at :datetime not null
# show_in_filters :boo... |
class HomeController < ApplicationController
def index
@body_id = "home"
@homepage = true
# feed
@top_article = Article.includes(:categories, :status).live.published.root.first if first_page?
@articles = Article.includes(:categories, :status).live.published.root.page(params[:page]).per(6).padd... |
# frozen_string_literal: true
module Halcyoninae
class CommandRegistry
def initialize(registries, arguments)
@registries = registries
@arguments = arguments
end
def find_command
command_name
end
private
attr_reader :registries, :arguments
def command_name
candid... |
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
describe Flickr do
before(:each) do
@flickr_auth = Flickr.new(Flickr.class_variable_get(:@@api_data)['api_key'], Flickr.class_variable_get(:@@api_data)['shared_secret'], Flickr.class_variable_get(:@@api_data)['auth_token'])
@flickr_norm = Flic... |
module ActionClient
class PreviewsController < ActionClient::ApplicationController
def show
client = ActionClient::Preview.find(params[:client_id])
action_name = params[:id]
if client.present? && client.exists?(action_name)
preview = client.new(action_name: action_name)
render ... |
class ChangeColumnOnMissions < ActiveRecord::Migration[5.2]
def change
remove_column :missions, :done
add_column :missions, :status, :integer, default: 0
end
end
|
class Changingtablname < ActiveRecord::Migration[5.1]
def change
drop_table :csm_info
end
end
|
require 'spec_helper'
describe CrazyHarry::Change do
# Change br to p
# Change b to h3 where b has text: "location"
# Change b to em where b inside p
#
# Add attribute: "partner" to all tags
#
# Another ADS suggestion. Not sure it if it needed for the first cut.
# Transform "lodging" to "... |
if defined?(ActionMailer)
class EventMailer < Devise::Mailer
include Devise::Controllers::UrlHelpers
include Devise::Mailers::Helpers
include Rails.application.routes.url_helpers
include Spree.railtie_routes_url_helpers
def event_created_submission(event_params, event, user)
date = event_p... |
class WrongNumberOfPlayersError < StandardError ; end
class NoSuchStrategyError < StandardError ; end
def validate_data(tournament)
raise WrongNumberOfPlayersError unless tournament.flatten.length % 2 == 0
end
# a method that takes a flat array and returns an array of two element
# strategies
def build_first_round(... |
require_relative 'errors'
require_relative 'session/commands'
require_relative 'session/hooks'
require 'forwarder'
module Lab42
module Tmux
class Session
attr_reader :commands, :configuration, :session_name, :window_number
extend Forwarder
forward_all :command, :query, to_object: Interface
... |
require "application_system_test_case"
class MeasuredIngredientsTest < ApplicationSystemTestCase
setup do
@measured_ingredient = measured_ingredients(:one)
end
test "visiting the index" do
visit measured_ingredients_url
assert_selector "h1", text: "Measured Ingredients"
end
test "creating a Mea... |
class Review < ApplicationRecord
belongs_to :myrecipe
belongs_to :user
# belongs_to :parent, :class_name => "Review", :foreign_key => "parent_review_id"
has_many :likes, dependent: :nullify
has_many :likers, through: :likes, source: :user
# has_many :child_events, :class_name => "Review", :foreign_key => "... |
FactoryBot.define do
factory :product do
name {"#{Faker::Lorem.word} #{Faker::Lorem.word}"}
description {Faker::Lorem.word}
end
end
|
# frozen_string_literal: true
require 'spec_helper'
class NestedExample < InfiniteSteps
operation(:variation1) do |o|
o.add_step 0, :method2
o.add_step 0, :method3
o.add_step 0, :method4
end
operation(:variation2) do |o|
o.add_step 0, :method1
o.nest operation(:variation1)
o.add_step 0,... |
#!/usr/bin/env ruby
require 'matrix'
class Board
@board
def initialize(str)
board = []
rows = str.split("\n")
@board = Matrix.rows(rows.map{|row| row.split("") })
end
def rows
@board.row_vectors
end
def cols
@board.column_vectors
end
def letter_win?(letter)
passes_vectors(l... |
class AlertsController < ApplicationController
before_action :authenticate_user!
def index
end
def new
@alert = Alert.new
end
def create
@alert = Alert.create(alert_params.merge(user: current_user))
redirect_to alert
end
def show
alert
end
def edit
alert
end
def update
... |
require 'csv'
require_relative 'students_data'
class Csvreader
attr_accessor :students
def initialize
@students = []
end
def read_in_csv_data(csv_file_name)
CSV.foreach(csv_file_name, headers: true) do |row|
@students << Student.new(row["NAME"], row["LAST_NAME"],row["GPA"],row["DEPT"])
end
... |
# encoding: UTF-8
require 'spec_helper'
require 'yt/models/video'
describe Yt::Video, :partner do
subject(:video) { Yt::Video.new id: id, auth: $content_owner }
context 'given a video of a partnered channel', :partner do
context 'managed by the authenticated Content Owner' do
let(:id) { ENV['YT_TEST_PAR... |
require 'rubygems'
Gem::Specification.new do |s|
s.name = 'enumerable-extra'
s.version = '0.2.0'
s.license = 'Artistic-2.0'
s.summary = 'Enhanced methods for Enumerable objects'
s.author = 'Daniel Berger'
s.email = 'djberg96@gmail.com'
s.homepage = 'https://github.com/djberg96/enumera... |
require 'spec_helper'
describe "occurences/new.html.erb" do
before(:each) do
assign(:occurence, stub_model(Occurence).as_new_record)
end
it "renders new occurence form" do
render
# Run the generator again with the --webrat flag if you want to use webrat matchers
assert_select "form", :action =>... |
require 'json'
require 'uri'
require 'net/http'
require 'fileutils'
require 'nokogiri'
FONT_AWESOME_CHEATSHEET_URL = 'http://fortawesome.github.io/Font-Awesome/cheatsheet/'
DOWNLOAD_DIR = './downloaded'
DOWNLOAD_FILENAME = "#{DOWNLOAD_DIR}/font-awesome-cheatsheet.html"
class FontAwesomePackagePopulator
def initiali... |
# frozen_string_literal: true
require 'spec_helper'
require 'apartment/elevators/first_subdomain'
describe Apartment::Elevators::FirstSubdomain do
describe 'subdomain' do
subject { described_class.new('test').parse_tenant_name(request) }
let(:request) { double(:request, host: "#{subdomain}.example.com") }
... |
require "gapbammon/version"
module Gapbammon
class Player
attr_accessor :name, :color
def initialize(name, color)
@name = name
@color = color.downcase
raise "Invalid color" unless ['red', 'black'].include? @color
end
def to_s
"#{@name} (#{@color})"
end
end
end
|
class CreateRateLimits < ActiveRecord::Migration
def change
create_table :rate_limits do |t|
t.integer :time
t.integer :requests
t.timestamps null: false
end
end
end
|
class Interest < ActiveRecord::Base
has_many :likes
has_many :users, through: :likes
attr_accessible :name
end
|
class AddRefNumberToBooking < ActiveRecord::Migration[5.0]
def change
add_column :bookings, :ref_number, :string
end
end
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Hyrax::ContactFormController, type: :controller do
let(:user) { User.new(email: 'test@example.com', guest: false) { |u| u.save!(validate: false) } }
let(:required_params) do
{
category: 'Depositing content',
name: 'Test Name',
... |
class Relationship
include Mongoid::Document
field :type, type: String
belongs_to :entity1, name: Entity
belongs_to :entity2, name: Entity
end
|
require File.dirname(__FILE__) + '/../test_helper'
require File.dirname(__FILE__) + '/../mocks/test/mock_http_response'
class ZenEventTest < ActiveSupport::TestCase
def setup
App.zen[:enabled] = true
@event = {:device => "ZenEventTest", :severity => 1, :summary => "Test event" }
end
def test_... |
# frozen_string_literal: true
require 'application_system_test_case'
class PhonesTest < ApplicationSystemTestCase
setup do
login_as(users(:one))
end
test 'create a phone, edit it and then delete it' do
visit phones_url
# Phones List (index)
assert_selector 'h1', text: 'Phones'
click_on 'Ne... |
class Customtype::MomentOfTheDay
def self.to_mongo value
case value
when 0
value = 'alba'
when 1
value = 'prima mattina'
when 2
value = 'tarda mattina'
when 3
value = 'mezzogiorno'
when 4
value = 'primo... |
require 'spec_helper'
describe Redpear::Store::List do
subject do
described_class.new "list:key", connection
end
let :other do
described_class.new 'other', connection
end
it { is_expected.to be_a(Redpear::Store::Enumerable) }
it 'should return all items' do
expect(subject.all).to eq([])
... |
require 'test_helper'
class StudentTest < ActiveSupport::TestCase
# relationships
should belong_to(:family)
should have_many(:registrations)
should have_many(:camps).through(:registrations)
# Validations
should validate_presence_of(:first_name)
should validate_presence_of(:last_name)
should validate... |
class DeleteInstantBookingProfileColumnsFromOtherModels < ActiveRecord::Migration
def up
remove_index :users, :subdomain
remove_column :users, :subdomain
remove_column :users, :advance_booking_days
remove_column :users, :default_appointment_length
remove_column :user_profiles, :about_us
... |
class Time
SECOND_PATTERN = %r{(?<second>[[:digit:]]{1,2})(?:\.(?<microsecond>[[:digit:]]+))?}
HOUR_MINUTE_SECOND_PATTERN = %r{(?<hour>[[:digit:]]{1,2}):(?<minute>[[:digit:]]{1,2}):#{SECOND_PATTERN}}
UTC_OFFSET_PATTERN = %r{(?<utc_offset>Z|(?<utc_offset_hours>[-+][[:digit:]]{1,2}):(?<utc_offset_minutes>[[:digit... |
require 'rails_helper'
describe "a logged in user" do
xit "can create a new performance" do
user = stub_login_user
visit user_performances_path(user)
click_on "Add Performance"
fill_in "Title", :with => "Recital"
fill_in "performance[date]", :with => "01/10/2017"
click_on "Add Performance... |
class ProjectsController < ApplicationController
def create
project = Project.new(project_params)
if project.save
head :created
else
render json: {errors: project.errors.full_messages}, status: :unprocessable_entity
end
end
def show
if requested_project.present?
render jso... |
json.array!(@categoriesproduits) do |categoriesproduit|
json.extract! categoriesproduit, :id, :nomcategorie
json.url categoriesproduit_url(categoriesproduit, format: :json)
end
|
class Image < ActiveRecord::Base
belongs_to :vehicle
has_attached_file :cover, styles: { :medium => "200x200", :tiny => "100x100" }, default_url: ("/img/missing.png")
validates_attachment_content_type :cover, :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"]
end
|
class Repository
attr_reader :name, :owner, :url, :description
def initialize(repository)
@name = repository["name"]
@owner = repository["owner"]["login"]
@url = repository["url"].sub("api.", "")
@description = repository["description"]
end
end
|
story %q(strip [_[^[:word:]]+ from the beginning and end of symlink names) do
status finished
points 1
created_by :unixsuperhero
assigned_to :unassigned
tags :cmd, :command, :rebuild
description <<-DESCRIPTION
Right now some of the symlinks' names are:
_something_holy_wow
_even_worse_
... |
module Categoryz3
class ChildItem < ActiveRecord::Base
belongs_to :category, inverse_of: :child_items, counter_cache: :child_items_count
belongs_to :master_item, class_name: 'Categoryz3::Item', inverse_of: :child_items
belongs_to :categorizable, polymorphic: true, inverse_of: :child_category_items
va... |
class Triangle
def initialize(side_1, side_2, side_3)
@side_1 = side_1
@side_2 = side_2
@side_3 = side_3
@triangle = [@side_1, @side_2, @side_3].sort
end
def not_a_triangle?
@triangle.any?{ |side| side <= 0} || @triangle[0] + @triangle[1] <= @triangle[2]
end
def kind
if not_a_triang... |
class PartiesController < ApplicationController
before_filter :authenticate_user!, except: [:index, :show]
before_filter :authenticate_host, only: [:edit, :update, :destroy]
# GET /parties
# GET /parties.json
def index
@parties = Party.all
if signed_in?
@user_res = UsersReservations.where("user_... |
#!/usr/bin/env ruby
require 'style_cop'
require 'optparse'
require 'rexml/document'
require 'highline'
options = {}
output = nil
opt = OptionParser.new do |opt|
opt.on('-s VAL', '--setting=VAL', '') { |v| options[:setting] = v }
opt.on('-f VAL', '--flags=VAL', '') { |v| options[:flags] = v }
opt.on('-c VAL', '-... |
class Comment < ApplicationRecord
belongs_to :ad_user , optional: true
belongs_to :st_user , optional: true
belongs_to :speak, optional: true
validates :ad_user_or_st_user,:text,:log_grade,:exp_grade,:cre_grade, presence: true
private
def ad_user_or_st_user
ad_user.presence or st_user.prese... |
load './initializer.rb'
class OnlineEvolution
def initialize
@world = World.new
end
def visualize
@world.print
end
def process_generation
GENERATION_DURATION.times do |generation_number|
puts "doing generation #{generation_number}"
animals = @world.animals
take_actions(animals)
end
end
def ... |
require 'spec_helper'
describe UsersController do
let!(:company) { FactoryGirl.create(:company, :with_owner) }
let(:valid_attributes) do
FactoryGirl.attributes_for(:user, company_id: company.id)
end
describe 'logged in ' do
before do
sign_in user
end
describe 'as GCES user' do
let... |
require 'rails_helper'
require 'byebug'
RSpec.describe KepplerFrontend::Urls::Front, type: :services do
context 'front urls' do
before(:all) do
@root = KepplerFrontend::Urls::Roots.new
@front = KepplerFrontend::Urls::Front.new
end
context 'view url' do
let(:result) {"#{@root.rocket_r... |
require File.expand_path(File.dirname(__FILE__) + "/qna_test_helper")
describe "AnswerQuestionTest" do
include QnaTestBase
before :each do
init_qna_pages
@product = product
@asker = user
@answerer = user
@question = question(@product, @asker)
if @qna_service.qa_moderation_enab... |
# encoding: utf-8
module Mail
class Part < Message
# Creates a new empty Content-ID field and inserts it in the correct order
# into the Header. The ContentIdField object will automatically generate
# a unique content ID if you try and encode it or output it to_s without
# specifying a content i... |
# We have 100 cars.
cars = 100
# We have 4 seats in each car
space_in_a_car = 4
# We have 30 drivers
drivers = 30
# We have 90 passengers
passengers = 90
# The number of cars not being driven = cars - drivers
cars_not_driven = cars - drivers
# The number of cars driven = drivers
cars_driven = drivers
# Our carpool capa... |
#!/usr/bin/env ruby
class XmasValidator
def initialize
@stream = []
end
def input(value)
return false if !valid_next_number?(value)
add_to_stream(value)
end
private
def valid_next_number?(value)
return true if @stream.length < 25
@stream.each_with_index do |num1, i|
next if num... |
module IControl::ARX
##
# The Volume Interface lets applications retrieve ARX volume information.
class Volume < IControl::Base
set_id_name "namespace"
##
# Returns the volume definitions for this volumes.
# @rspec_example
# @return [VolumeDefinition]
# @param [Hash] opts
# @option o... |
Itbanks::Application.routes.draw do
devise_for :users, path_names: {sign_up: "registration", sign_in: "login", sign_out: "logout"}
resources :users, :only => ["show"]
resources :companies, path: "s"
resources :feed_entries, path: "n"
resource :search, :only => :show, :controller => :search
root :to => 'f... |
require_relative 'RDT'
require_relative 'WinBoxes'
require_relative 'MechReporter'
class Booking < RDT
include WinBoxes
attr_accessor :data, :warranty, :error, :preadvice, :excel
def initialize( test = false )
super(test)
self.test = test
self.data = {}
temp = %w{username password}
un... |
require "socket"
require "test/unit"
module SocketTest
def setup
@host = ENV["TEST_HOST"] || '127.0.0.1'
@srv = TCPServer.new(@host, 0)
@port = @srv.addr[1]
end
def test_start
sock = MogileFS::Socket.start(@host, @port)
assert_instance_of MogileFS::Socket, sock, sock.inspect
assert_nothi... |
class CuisineSerializer < ActiveModel::Serializer
attributes :id, :name, :photo_url, :yelp_recommendation
has_many :restaurants
def yelp_recommendation
yelp_search_recommendation = YelpSearch.new("Boston")
recommendations = yelp_search_recommendation.suggestion_from_yelp(object.name)
end
end
|
require "rspec"
require 'game_logic'
describe GameLogic do
it "Makes a move on turn 2" do
newGame=GameLogic.new
newGame.computerMoveSecond([0,0,0,2,0,0,0,0,0],2).should==4
end
it "Makes 0 move on turn 4" do
newGame=GameLogic.new
newGame.moveOptions=0
newGame.computerMoveSecond([0,0,2,2,1,0,0... |
#!/usr/bin/env jruby
require 'fileutils'
remoteRequire 'installerLogger'
remoteRequire 'networkHelper'
remoteRequire 'components/gnuBuild'
remoteRequire 'ioHelpers'
remoteRequire 'osHelpers'
class DnsServer < GnuBuild
def initialize
super
@settings = COMPONENT_OPTIONS.dnsServer
end
def alreadyInstall... |
module Wrangler
# handles notifying (sending emails) for the wrangler gem. configuration for
# the class is set in an initializer via the configure() method, e.g.
#
# Wrangler::ExceptionNotifier.configure do |config|
# config[:key] = value
# end
#
# see README or source code for possible values and de... |
# all api calls require a user to be specified
# can call locally like this: curl --data 'my update to you' "localhost:9393/api/doing?user=bob@gmail.com"
before '/api/*' do
halt 400, "Invalid request" unless User.exists?(:name => params[:user])
end
get '/api/test' do
# do nothing here
end
get '/api/version' do
... |
# frozen_string_literal: true
class Car
attr_accessor :max_acceleration, :max_speed, :current_speed, :location
def initialize(max_acc)
@max_acceleration = max_acc
@max_speed = 3
@current_speed = 0
@location = 0
end
def move
@current_speed += @max_acceleration if @current_speed < @max_speed... |
class AddApiValueToPosts < ActiveRecord::Migration[5.2]
def change
add_column :posts, :isbn, :bigint, after: :content
add_column :posts, :title, :string, after: :isbn
add_column :posts, :image_url, :string, after: :title
add_column :posts, :url, :string, after: :image_url
add_index :posts, :title
... |
require 'spec_helper'
RSpec.describe BabySqueel::Calculation do
let(:table) { Arel::Table.new('posts') }
describe '#node' do
it 'reads the attribute' do
calculation = described_class.new(table[:id])
expect(calculation.node).to eq(table[:id])
end
end
describe '#to_s' do
it 'generates a... |
# This migration comes from refinery_image_slideshows (originally 4)
class AddJsConfigToImageSlideshows < ActiveRecord::Migration
def change
add_column :refinery_image_slideshows, :js_config, :text
end
end |
class ConcertsController < ApplicationController
before_action :authenticate_user!, except: [:index, :show]
before_action :set_concert, only: [:show, :edit, :update, :destroy]
def index
@concerts_today = Concert.concerts_today(8)
@concerts_later = Concert.concerts_later(4)
end
def show
@comment ... |
module RailsProperties
# In Rails 3, attributes can be protected by `attr_accessible` and `attr_protected`
# In Rails 4, attributes can be protected by using the gem `protected_attributes`
# In Rails 5, protecting attributes is obsolete (there are `StrongParameters` only)
def self.can_protect_attributes?
(A... |
require 'rails_helper'
describe WegoauditObjectLookup do
class WegoauditObjectLookupTestClass
include WegoauditObjectLookup
def self.all
end
end
describe '.by_api_name' do
it 'lazy loads records only once and performs a lookup' do
object1 = double(api_name: 'foo')
object2 = double(a... |
class KondatesController < ApplicationController
before_action :set_yesterday_kondates, only: [:new, :create]
def show
kondate_histories = session[:kondate_histories]
kondate_histories = KondateHistory.histories_for_user(current_user) if current_user.present?
@kondates = Kondate.kondates_by_kondate_hi... |
class Attachment
attr_reader :id
attr_reader :filename
def initialize(active_storage_attachment)
@id = active_storage_attachment.id
@filename = active_storage_attachment.filename
end
end
|
require 'spec_helper'
describe GroupDocs::Storage::Package do
it_behaves_like GroupDocs::Api::Entity
it { should have_accessor(:name) }
it { should have_accessor(:objects) }
describe '#add' do
it 'adds objects to be packed later' do
subject.objects = ['object 1']
subject.objects.should_re... |
require 'spec_helper'
describe SubmissionsController do
describe 'routing' do
it 'routes to #index' do
expect(get('/mailings/1/submissions')).to route_to('submissions#index', mailing_id: '1')
end
it 'routes to #new' do
expect(get('/mailings/1/submissions/new')).to route_to('submissions#new',... |
class AddPlayersCountToTeams < ActiveRecord::Migration[5.0]
def change
add_column :teams, :players_count, :integer, default: 0, null: false
Team.select(:id).find_each do |roster|
Team.reset_counters(roster.id, :players)
end
end
end
|
# frozen_string_literal: true
Given('I am on the MediData home page') do
visit '/'
end
Then('I should be redirected to Novo Perfil page') do
expect(page).to have_current_path(new_profile_path)
end
Given('I am on Novo Perfil page') do
visit new_profile_path
end
Then('A New Profile with {string} email should be ... |
class Fluentd
class Agent
class TdAgent
include Common
def self.default_options
{
:pid_file => "/var/run/td-agent/td-agent.pid",
:log_file => "/var/log/td-agent/td-agent.log",
:config_file => "/etc/td-agent/td-agent.conf",
}
end
def version
... |
class GithubRepo
attr_reader :name, :full_name, :description
def self.for_user(token)
GithubService.new(token).repos.map do |raw_repo|
GithubRepo.new(raw_repo)
end
end
end
|
# TODO: This is just a stub for now
require 'signatures/openlogon_signature'
class OpensignSignatureFactory
def self.generate_opensign_signature(login_data)
OpenlogonSignature.new
end
end |
class Category < ActiveRecord::Base
has_many :posts
validates :name, uniqueness: true
validates :name, presence: true
def self.get(params)
Category.where(name: params[:category]).first
end
def self.new_category(params)
Category.create(name: params[:name])
end
def edit(category_id, updates)
... |
class Admin::AccountsController < ApplicationController
before_action :require_admin
def index
@query = params[:q]
@filtered = params[:without_avatar].present? || params[:without_matches].present? ||
params[:deletable].present? || params[:with_matches].present?
@accounts = search_or_list_accounts... |
class Badge < ActiveRecord::Base
has_many :badge_users
has_many :users, through: :badge_users
belongs_to :video
validates_presence_of :name
validates_numericality_of :video_id, allow_blank: true
validates_numericality_of :min_views, allow_blank: true
validate :has_condition
def applicable_to? user
... |
class BusinessesController < ApplicationController
before_action :check_for_login, :only => [:show, :invite, :new, :create]
before_action :check_for_access, :only => [:show, :invite]
before_action :check_for_admin, :only => [:invite]
def show
@business = Business.find params[:id]
reports = @business.r... |
require 'easy_extensions/external_resources/sync_base'
module EasyExtensions
class ExternalResources::ImportSyncBase < ExternalResources::SyncBase
def initialize(new_record_attributes={})
@new_record_attributes = new_record_attributes || {}
end
def sync_all
self.class.logger.info "*********... |
module XBee
module Frame
module Meta
module Static
attr_accessor :template
attr_accessor :frame_type
def from_bytes(bytes)
_, data_size, frame_type = bytes.unpack 'CS>C'
matrix = self.template.reduce '' do |head, field|
head + (field[1][0] == '*' ? f... |
require 'net/http'
module Bitly
API_BASE_URL = 'https://api-ssl.bitly.com/v4/'
# 汎用APIcall
def call(method: :post, path: "", params: nil)
uri = URI.join(API_BASE_URL, path)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
req = Net::... |
# -*- encoding : utf-8 -*-
class AddLimiteToUsuario < ActiveRecord::Migration
def change
add_column :usuarios, :limite, :integer
end
end
|
class AddDeniedByToGrantApplication < ActiveRecord::Migration
def change
add_column :grant_applications, :denied_by, :text, array: true, default: []
end
end
|
require "factory_bot"
class DownloadLinkMailerPreview < ActionMailer::Preview
def send_link
DownloadLinkMailer.send_link(
recipient: FactoryBot.build(:beis_user, email: "beis@example.com"),
file_name: "spending_breakdown.csv"
)
end
def send_failure_notification
DownloadLinkMailer.send_fa... |
class Schedule < ActiveRecord::Base
belongs_to :association
has_many :teams
end
|
class Bicycle < Product
has_many :bicycle_images, class_name: 'BicycleImage', dependent: :destroy
accepts_nested_attributes_for :bicycle_images
attr_accessible :bicycle_images_attributes
end
|
class Passenger < ActiveRecord::Base
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, format: {with: VALID_EMAIL_REGEX}
has_many :bookings, through: :user_bookings
has_many :user_bookings
has_many :tour_times, through: :bookings
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.