text stringlengths 10 2.61M |
|---|
class CohortsController < ApplicationController
before_action :require_user , except: [:destroy]
def new
@instructors = Instructor.all
@students = Student.all
@courses = Course.all
@cohort = Cohort.new
end
def create
@instructors = Instructor.all
@students = Student.all
@courses = ... |
require "spec_helper"
describe Geotab::Device do
let(:client) { Geotab::Client.new }
before :each do
VCR.use_cassette "device/connection", match_requests_on: [:host, :path] do
client.authenticate("username", "password", "database")
end
end
describe ".all" do
it "should return an array of de... |
module Yakitori
# 重み付け定数による計算でホットエントリ度合いを算出
module WeightingCalculator
STAR_GRAVITY = 1.0
COMMENT_GRAVITY = 1.2
WATCHERS_GRAVITY = 0.2
GRAVITY = 1.5
class << self
def calc(post)
created_at = post['created_at']
watchers_count = post['watchers_count']
star_count = po... |
class Sensor < ApplicationRecord
belongs_to :user
has_many :readings
validates :name, uniqueness: true, presence: true
def self.find_from_params(params)
find_by name: params[:name]
end
def self.create_from_params(params)
user = User.find_by email: params[:email]
name = params[:name]
senso... |
require "rails_helper"
RSpec.describe Admin::DistrictsController, type: :routing do
describe "routing" do
it "routes to #index" do
expect(:get => "/admin/districts").to route_to("admin/districts#index")
end
it "routes to #new" do
expect(:get => "/admin/districts/new").to route_to("admin/dis... |
class Cart < ActiveRecord::Base
has_many :line_items, dependent: :destroy
def add_product(product_id)
lineItem = line_items.find_by(product_id: product_id)
if lineItem
lineItem.quantity +=1
else
lineItem = line_items.build(product_id: product_id)
end
# update to use new price
... |
require "test_helper"
describe Person do
let(:person) { Person.new }
should belong_to(:household)
should have_many(:vehicles).dependent(:destroy)
end
|
class Blogger < ApplicationRecord
has_many :posts
has_many :destinations, through: :posts
validates :name, uniqueness: true
end
|
require_relative 'value_combiner'
class LastRealValueWinsCombiner < ValueCombiner
AFFECTED_ATTRIBUTES = ['Last Avg CPC', 'Last Avg Pos']
private
def combine!(key)
@hash[key] = @hash[key].select {|v| not (v.nil? or v == 0 or v == '0' or v == '')}.last
end
end |
class CommentsController < ApplicationController
def create
@article=Article.find(params[:article_id])
@comment=@article.comments.create(comment_params)
redirect_to article_path(@article)
end
private
def comment_params
params.require(:comment).permit(:author_name, :content)
end
end |
class AnswersController < ApplicationController
before_action :authenticate, only: :new
def new
@question = Question.find(params[:question_id])
@answer = Answer.new
end
def create
@question = Question.find(params[:question_id])
@answer = @question.answers.build(answer_params)
@answer.code = pa... |
# frozen_string_literal: true
module Ruboty
module Github
module Actions
class SearchIssues < Base
def call
if has_access_token?
search
else
require_access_token
end
end
private
def search
results = search_iss... |
json.album do |json|
json.extract! @album, :id, :title
json.images do |json|
json.array!(@album.images) do |image|
json.extract! image, :instagram_id, :ig_url, :ig_caption, :ig_user, :ig_user_avatar, :ig_video_url, :ig_created_time
end
end
end |
# == Schema Information
# Schema version: 20110313064440
#
# Table name: short_urls_log
#
# id :integer(4) not null, primary key
# url :string(255)
# ip_address :string(255)
# created_at :datetime
# updated_at :datetime
#
class ShortUrlsLog < ActiveRecord::Base
def self.table_name() "short_u... |
FactoryGirl.define do
factory :chartboost_instance do
sequence(:user_id) { |n| "0000#{n}" }
sequence(:platform) { |n| "platform_#{n}" }
sequence(:to_app_name) { |n| "to_app_name_#{n}" }
sequence(:to_app_id) { |n| "to_app_id_#{n}" }
sequence(:to_company_name) { |n| "to_company_name_#{n}" }
... |
require 'spec_helper'
describe SearchesController do
context "handling GET search.xml" do
before do
@search = Search.create!(:name => 'blah')
end
it "should try to retrieve the xml for the search" do
get :show, { :id => @search.id, :format => 'xml' }
response.content_type.should == "a... |
class Users::RegistrationsController < Devise::RegistrationsController
layout 'aquila'
after_filter :create_member_collaboration, only: :create
def create_member_collaboration
Collaborations.create_after_registration(current_member)
end
end
|
# frozen_string_literal: true
# Devise User Controller
class AccountController < Devise::RegistrationsController
before_action :require_no_sso!, only: %i[new create]
def new
super
end
def edit
redirect_to setting_path
end
# POST /resource
def create
if Setting.has_module? :github and Sett... |
require 'test/unit'
require_relative 'fizz_buzz'
class TestFizzBuzz < Test::Unit::TestCase
def setup
@fizz_buzz = FizzBuzz.new
end
def test_fizz
sample = [3, 6, 9, 12]
sample.each do |s|
expected = @fizz_buzz.play s
assert_equal expected, "Fizz"
end
end
def test_buzz
sampl... |
puts "Escreva um programa que calcula e exiba na tela:"
segundos = 60
minuto_em_segundos = 60
dia_em_horas = 24
ano_em_meses = 12
ano_em_dias = 365
decada = 10
idade_natalia = 34
idade = 1232000000.0
expectativa_de_vida = 80
chocolate = 5
puts "- quantas horas há em um ano?"
puts dia_em_horas * ano_em_dias
puts
puts ... |
require 'rails_helper'
require 'spec_helper'
feature "creating tickets" do
before do
@project = FactoryGirl.create(:project)
@user = FactoryGirl.create(:user)
# Click "New Ticket", and must show "login" message when ther is no session.
visit "/"
click_link @project.name
click_link "New Ticket"
expect(... |
# frozen_string_literal: true
# Flattens labels
class Array
def flatten_labels
map do |value|
if value.is_a? Hash
value.flatten_labels
else
value
end
end
end
end
|
class StatGrabber
def self.run(user)
begin
twitter_client = user.twitter_client
friends = twitter_client.friend_ids(user.uid.to_i)
real_friends = friends.attrs[:ids]
real_friends.each do |id|
... |
class AddAttachmentCertificateToWorkCertificates < ActiveRecord::Migration
def self.up
change_table :work_certificates do |t|
t.attachment :certificate
end
end
def self.down
remove_attachment :work_certificates, :certificate
end
end
|
class RenameTotal < ActiveRecord::Migration
def up
rename_column :quarters, :total, :total_savings
end
def down
end
end
|
json.animes do
@anime.each do |anime|
json.set! anime.id do
json.extract! anime, :id, :title, :description, :genre
if anime.photo.attached?
json.photo_url url_for(anime.photo)
else
json.photo_url ""
end
end
end
end
... |
class Planet
attr_reader :name, :color, :mass_kg, :distance_from_sun_km, :fun_fact
def initialize(name, color, mass_kg, distance_from_sun_km, fun_fact)
raise ArgumentError.new("Planet's mass should be greater than zero.") unless mass_kg.respond_to?(:>) && mass_kg > 0
raise ArgumentError.new("Distance from... |
describe CommentDecorator do
describe '.added_date' do
let(:comment){ create(:comment, created_at: Time.zone.parse('2016-06-23 14:30:00')).decorate }
it 'has correct added date' do
expect(comment.added_date).to eq('23-06-2016, 14:30')
end
end
end
|
class FontPhudu < Formula
head "https://github.com/google/fonts/raw/main/ofl/phudu/Phudu%5Bwght%5D.ttf"
desc "Phudu"
homepage "https://github.com/duongtrtype/DTPhudu"
def install
(share/"fonts").install "Phudu[wght].ttf"
end
test do
end
end
|
require 'test_helper'
module Nestable::Strategy::Mock; end
module Nestable::Strategy::Mock2; end
module Nestable::Strategy::Mock3; end
class Nest < ActiveRecord::Base
end
class NestableTest < Test::Unit::TestCase
def setup
setup_tables
end
def test_should_implement_interface
Nest.nestable
assert N... |
class LotVersion < ActiveRecord::Base
attr_accessible :lot_id, :comments, :technician_id
attr_accessible :samples_attributes
belongs_to :lot
has_many :samples, order: :created_at, dependent: :destroy
belongs_to :technician
accepts_nested_attributes_for :samples, allow_destroy: true
validates :techni... |
class Room < ApplicationRecord
has_many :meetings, dependent: :destroy
belongs_to :location
end
|
class RequisicoesController < ApplicationController
# GET /requisicoes
def index
@requisicoes = @empresa.requisicoes.find_all_by_estado(:pendente)
end
# GET /requisicoes/new
def new
@requisicao = @empresa.requisicoes.build
end
# GET /requisicoes/1/edit
def edit
@requisicao = @empresa.requi... |
class FontArkPixel10pxMonospaced < Formula
version "2022.12.20"
sha256 "a0ffe5ac07aff5455652c16ea7e33e9b18635e3f717104ca23fae1ede6e5fbea"
url "https://github.com/TakWolf/ark-pixel-font/releases/download/#{version}/ark-pixel-font-10px-monospaced-otf-v#{version}.zip"
desc "Ark Pixel 10px monospaced"
desc "Open ... |
class Redpanda < Formula
desc "Fastest Queue in the West"
homepage "https://www.vectorized.io"
url "https://github.com/rkruze/redpanda/releases/download/v22.1.5/rpk-darwin-amd64.zip"
version "22.1.5"
sha256 "1dccd2012619be0fd79b6b1985cd727a2717dc2e5643d55521c2ef1739aad9ce"
bottle :unneeded
... |
Bundler.require
require 'securerandom'
require 'yaml'
class Oscars < Sinatra::Base
set :root, File.dirname(__FILE__)
enable :sessions
helpers Sinatra::Cookies
register Sinatra::AssetPack
register Sinatra::ActiveRecordExtension
register Sinatra::Flash
I18n.config.enforce_available_locales = true
asse... |
# Use this file to easily define all of your cron jobs.
#
# It's helpful, but not entirely necessary to understand cron before proceeding.
# http://en.wikipedia.org/wiki/Cron
# Example:
#
# set :output, "/path/to/my/cron_log.log"
#
# every 2.hours do
# command "/usr/bin/some_great_command"
# runner "MyModel.some_m... |
module NestedSend
class Checker
def self.kind_of_collection(attribute)
return :sym_hash if is_symbolized_hash?(attribute)
return :str_hash if is_complete_string?(attribute)
return :array if is_stringified_array?(attribute)
return false
end
def self.kind_of_attribute(kind)
re... |
class Task < ApplicationRecord
belongs_to :epic
has_many :user_tasks
has_many :users, through: :user_tasks
end
|
Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
# thing routes
get '/things', to: 'things#index'
get '/things/:id', to: 'things#show'
post '/things', to: 'things#create'
delete '/things/:id', to: 'things#delete'
put '/thi... |
# Read about factories at https://github.com/thoughtbot/factory_girl
FactoryGirl.define do
factory :user do
sequence(:email) { |n| "hw_#{n}@yopmail.com" }
password "123456"
password_confirmation "123456"
password_hash ""
password_salt ""
admin false
registration_token ""
verified tru... |
require_relative 'io/line_by_line_reader'
require_relative 'io/log_parser_printer'
require_relative 'groupers/grouper_factory'
require_relative 'orderers/orderer_factory'
module SmartLogParser
class LogParser
attr_reader :log_file, :group_and_order_array
DEFAULT_GROUP_AND_ORDER = ['PAC-down', 'UPAC-down']
... |
Spree::Variant.class_eval do
has_many :sale_prices, through: :prices
delegate_belongs_to :default_price, :sale_price, :original_price, :on_sale?
def put_on_sale value, params={}
if !params[:currency] or params[:currency] == 'all_currencies' or params[:currency] == :all_currencies
run_on_prices(true) ... |
default[:cc_rails_app][:user] = "cc"
default[:cc_rails_app][:checkout] = true
# portal specific defaults
default[:cc_rails_app][:portal][:theme] = "xproject"
default[:cc_rails_app][:portal][:name] = "Cross Project Portal"
default[:cc_rails_app][:portal][:source_url] = "git://github.com/concord-consortium/rigse.git"
de... |
class RemoveNullUserActivityStatus < ActiveRecord::Migration[5.1]
def up
change_column_null(:users, :activity_status, false, true )
change_column(:users, :activity_status, :boolean, :default => true)
end
end
|
class PostsController < ApplicationController
def index
@post = Post.all
@vote = Vote.new
end
def new
@post = Post.new
end
def create
@post = current_user.posts.create(post_params)
if @post.save
flash[:success] = "Link Posted!"
redirect_to posts_path
else
flash[:da... |
class Item < ApplicationRecord
acts_as_copy_target
belongs_to :merchant
has_many :invoice_items
has_many :invoices, through: :invoice_items
def self.find_item(params)
find_by(params)
end
def self.find_all(params)
where(params)
end
def self.most_revenue(quantity = 5)
joins(invoice_items:... |
class Qpdf < Formula
desc "Tools for and transforming and inspecting PDF files"
homepage "https://qpdf.sourceforge.io/"
url "https://downloads.sourceforge.net/project/qpdf/qpdf/8.0.2/qpdf-8.0.2.tar.gz"
sha256 "b09e1730b515956903866619b466da359cc051ae8c9d8690d8e7a2aca493c8c1"
bottle do
cellar :any
sha... |
class Payment < ApplicationRecord
belongs_to :account
belongs_to :utility
validates :amount, presence: true
validates :tariff, presence: true
validates :quantity, presence: true
end
|
# frozen_string_literal: true
module GraphQL
module Analysis
module AST
class MaxQueryDepth < QueryDepth
def result
configured_max_depth = if query
query.max_depth
else
multiplex.schema.max_depth
end
if configured_max_depth && @max_dep... |
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
describe 'Japanese()' do
describe 'Argument errors' do
it 'throws error when arg is not String object' do
NotString = Class.new
not_string = NotString.new
lambda {
Japanese(not_string)
... |
module Omniship #:nodoc:
class Package
include Quantified
cattr_accessor :default_options
attr_reader :options,
:value,
:currency
# Package.new(100, [10, 20, 30], :units => :metric)
# Package.new(Mass.new(100, :grams), [10, 20, 30].map {|m| Length.new(m, :centimetres)}... |
module Antlr4::Runtime
class StarLoopEntryState < DecisionState
attr_accessor :loopback_state
attr_accessor :is_precedence_pecision
def initialize
super
@loopback_state = nil
@is_precedence_pecision = false
end
def state_type
STAR_LOOP_ENTRY
end
end
end |
class Indirizzimac < ActiveRecord::Base
VALID_MACADDRESS_REGEX = /\A([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})\z/i
belongs_to :employee
belongs_to :vlan
default_scope -> { order(:created_at) }
validates :employee_id, presence: true
validates :vlan_id, presence: true
validates :hostname, presence: true,... |
class UsersController < ApplicationController
def index
@users = User.all
end
def show
@post = Post.new
@posts = @user.posts.order('created_at DESC')
end
private
def set_user
@user = User.find_by(email: params[:id])
end
end
|
module Enumerable
def my_each
for i in 0...self.length do
yield(at(i))
end
self
end
def my_each_with_index
for i in 0...self.length do
yield(at(i), i)
end
self
end
def my_select
ret = []
self.my_each { |x| ret.push(x) if yield(x) }
ret
end
def my_all?(&bl... |
require 'cinch'
class Memo < Struct.new(:nick, :channel, :text, :time)
def to_s
"[#{time.asctime}] <#{channel}/#{nick}> #{text}"
end
end
$memos = {}
class MemoPlugin
include Cinch::Plugin
attr_accessor :memos
match /memo (.+?) (.+)/
match /.*/, :method => :consume, :use_prefix => false
def consume(m)
i... |
class Item < ActiveRecord::Base
belongs_to :user
belongs_to :category
has_many :line_items
def self.available_items
all.where("inventory > ?", 0)
end
def display_price
self.price.to_f/100
end
def inventory_low?
self.inventory < 5
end
end
|
json.array!(@imageposts) do |imagepost|
json.extract! imagepost, :id, :name, :comment
json.url imagepost_url(imagepost, format: :json)
end
|
require 'rails_helper'
describe 'admin/fit_bit_stats/index' do
let(:fit_bit_stats) { create(:fit_bit_stats, steps: 1234, floors: 56) }
let(:fit_bit_history) do
[
create(:fit_bit_stats, steps: 1011, floors: 4),
create(:fit_bit_stats, steps: 789, floors: 3),
create(:fit_bit_stats, steps: 456, f... |
# -*- encoding : utf-8 -*-
class CreateViews < ActiveRecord::Migration
def change
create_table :views do |t|
t.references :church, index: true, foreign_key: true, null: false
t.string :applies_to, null: false
t.string :name, null: false
t.string :fields, array: true, null: false
t.t... |
require "game_of_life/version"
require 'byebug'
module GameOfLife
class Grid
attr_accessor :cells
def initialize(pattern: nil, coordinates: nil)
if pattern
@cells = build_cells_from_pattern(pattern)
elsif coordinates.any?
@cells = build_cells_from_coordinates(coordinates)
... |
class AddMonthlyPaymentToAccounts < ActiveRecord::Migration[5.1]
def change
add_column :accounts, :monthly_payment, :float, default: 0
end
end
|
module SkillsHelper
def summarize_skills_by_category(categories)
content_tag :table do
caption = content_tag :caption, 'Technical Skills by Category'
thead = content_tag :thead do
content_tag :tr do
categories.keys.inject('') do |r, k|
r + content_tag(:th, h(k))
... |
# -*- encoding : utf-8 -*-
require 'rubygems'
require 'mechanize'
require 'logger'
require 'hpricot'
require 'optparse'
require 'optparse/time'
require 'ostruct'
require 'rufus/scheduler'
require "highline/system_extensions"
include HighLine::SystemExtensions
load "Tribal.rb"
options = OpenStruct.new
options.library... |
module HasGlobalSession
# Indicates that the global session configuration file is missing from disk.
#
class MissingConfiguration < Exception; end
# Indicates that the global session configuration file is missing elements or is
# malformatted.
#
class ConfigurationError < Exception; end
# Indicates th... |
class SearchController < ApplicationController
def show
return panlexicon unless search_query
return redirect_to(action: 'show', query: search_query) if request.post?
@search = Search.new(search_query)
# if @search.valid?
# else
# end
# respond_to do |format|
# if @search.save
... |
class CreateLoadBanlancers < ActiveRecord::Migration
# 负载均衡器 load_balancer
#
#内存 mem
#端口数量 port_qty
#cpu
#cpu 数量 cpu_qty
#电源模块数量 power_module_qty
#工作层数 layer
def self.up
create_table :load_banlancers do |t|
t.integer "mem"
t.integer "port_qty"
t.string "cpu"
t.integer "cpu_qty"
... |
class Board
attr_reader :size
def initialize(n)
@grid = Array.new(n) { Array.new(n, :N) }
@size = n * n
end
def self.print_grid(grid) # => [:S, :N],[:X, :S]
grid.each do |row|
puts row.join(" ")
end
end
def [](position)
# separate row and column... |
require 'rubygems'
require 'rest_client'
require 'xmlsimple'
class Rest
def initialize(url, username, password)
@uri = "https://#{username}:#{password}@#{url}"
@username = username
@password = password
@job_id = nil
@path_to_file = ""
end
def add_file(filename, path_to_file)
@filename = filename
@pa... |
class PollOption < ActiveRecord::Base
belongs_to:poll_question
validates_presence_of :option
end
|
require 'capybara'
require 'capybara/dsl'
require 'capybara/selenium/driver'
require 'cgi'
require 'optparse'
module HarvestReport
class Runner
include Capybara::DSL
def self.run(*args)
new(ARGV).run
end
def initialize(args)
@options = {
:download_dir => '/tmp/harvest_report... |
# As a maker
# In order to start a conversation as a maker
# I want to reply to a peep from another maker.
feature 'Reply to a message' do
before do
sign_up
log_in
post_message
log_out
sign_up_2
log_in_2
end
scenario 'displays a reply button' do
expect(page).to have_link 'Reply'
end... |
require 'rails_helper'
RSpec.describe BookingsController, :type => :controller do
describe 'GET #show' do
context 'when user is not logged in' do
before do
car = create(:car)
booking = create(:booking)
login_with nil
get :show, car_id: car.id, id: booking.id
end
... |
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :require_login
private
def require_login
unless session[:user_id]
flash[:status] = :failure
flash[:message] = "You must be logged in to access this section"
redirect_to root_path, s... |
# 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' },])
# ... |
class CreateDb < ActiveRecord::Migration[5.0]
def change
create_table "absences", primary_key: "ID", id: :bigint, force: :cascade, options: "ENGINE=MyISAM DEFAULT CHARSET=latin1" do |t|
t.string "Username", limit: 50
t.string "StoreID", limit: 50
t.string "Absence", limit: 10, null: false
... |
class AddBatchIdToAdvanceFeeCollections < ActiveRecord::Migration
def self.up
add_column :advance_fee_collections, :batch_id, :integer, :null => true, :default => nil
end
def self.down
remove_column :advance_fee_collections, :batch_id, :integer
end
end
|
# Victor Costan:
# dropped because it wasn't hooked up to the rest of the code
# preserved to move all the features into the new ca.rb / ecert.rb
require 'tem_ruby'
require 'test/unit'
require 'openssl'
# Integration work by Victor Costan
#Author: Jorge de la Garza (MIT '08), mongoose08@alum.mit.e... |
require 'spec_helper'
describe "Static pages" do
subject { page }
# See Listing 5.39
shared_examples_for "all static pages" do
it { should have_selector('h1', text: heading) }
end
describe "Home page" do
#This tells the test (Capybara) to visit the home page as described in the routes.rb file
before ... |
namespace :elasticsearch do
desc 'Reindex all'
task reindex: :environment do
on roles :web do
run "cd /var/www/nzen/current && bundle exec rake searchkick:reindex:all"
end
end
%w[start stop restart].each do |command|
desc "#{command} elasticsearch"
task command do
on roles :web do
... |
# provided MySQL Client Gem
class Client
attr_accessor :con
def initialize(con)
@con = con
end
def do_some_dml
puts "record saved in #{@con}"
true
end
end
|
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec'
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{composition_engine}
s.version = "0.0.0"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :requ... |
=begin
#===============================================================================
Title: Restricted Move Input
Author: Hime
Date: Aug 31, 2013
--------------------------------------------------------------------------------
** Change log
Aug 31, 2013
- Initial release
-------------------------------------... |
class ContactMessagesController < ApplicationController
load_and_authorize_resource :user,:only=>[:index]
# GET /contact_messages
# GET /contact_messages.json
def index
layout=layout_chooser(@user)
@contact_messages = ContactMessage.all
respond_to do |format|
format.html do
render :... |
class Api::EventsController < ApplicationController
include JSONAPI::ActsAsResourceController
def index
if params[:upcoming]
event = Event.where('start_time >= :date', date: Date.today).order('start_time ASC').take(3)
event_resources = event.map{ |e| Api::EventResource.new(e, nil)}
event_resou... |
class AddCorrectToGameQuestionAnswer < ActiveRecord::Migration
def change
add_column :game_question_answers, :correct, :boolean
add_index :game_question_answers, :correct
end
end
|
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :timeoutable, :validatable
attr_accessible :email, :password, :password_confirmation, :remember_me, :profile_id, :profile_type
belongs_to :profile, polymorphic: true
has_many :pho... |
# encoding: utf-8
class EventWinesController < ApplicationController
include Helper::EventsControllerHelper
before_filter :get_event
before_filter :authenticate_user!
before_filter :check_owner
def new
@old_event = Event.find(params[:event_id]) # 这里不用get_event 是为了避免下面的代码产生空对象
@event_wine = @event.... |
module ProductRepresenter
include Roar::JSON
property :id
property :name
property :price
property :stock
end
|
# frozen_string_literal: true
class User
module Dues
extend ActiveSupport::Concern
def dues
if parent.present?
{ user_id: parent_id }
elsif children.blank?
89
else
133 + children.count
end
end
def dues_due?
return false if parent_id.present?
... |
# encoding: UTF-8
# Copyright 2012 Twitter, Inc
# http://www.apache.org/licenses/LICENSE-2.0
require 'nokogiri'
require 'fileutils'
require 'parallel'
require 'etc'
require 'set'
module TwitterCldr
module Resources
class NumberFormatsImporter < Importer
requirement :cldr, Versions.cldr_version
ou... |
class Mutations::DeleteAuthor < GraphQL::Function
argument :id, types.ID
#what the call returns
type types.Boolean
# sample query for delete author
# mutation {
# deleteAuthor(id: 6) {}
# }
def call(obj, args, ctx)
author = Author.find(args[:id])
!!author.destroy
end
end
|
class CrossValidation
attr_reader :facebook_info
attr_reader :linkedin_info
attr_reader :document_info
attr_reader :user
def initialize(user)
@user = user
@facebook_info = user.last_log(:facebook).request_content
@linkedin_info = user.last_log(:linkedin).request_content
@document_info = user.... |
class Category < ApplicationRecord
# associations
has_many :products
# validations
validates :name, length: { in: 2..100 }, uniqueness: true, presence: true
end
|
class Api::V1::ItemsController < ApplicationController
respond_to :json
def index
respond_with Item.all, select_attributes
end
def show
item = Item.find(params[:id])
respond_with item, select_attributes
end
def destroy
respond_with Item.delete(params[:id])
end
def create
item = It... |
class Trip < ActiveRecord::Base
has_many :trip_places
def from_elasticsearch(trip)
self.id = trip['id']
self.url = trip['url']
self.name = trip['name']
self.description = trip['description']
end
def to_elasticsearch
{
id: self.id,
url: self.url,
name: self.name,
des... |
class SessionsController < ApplicationController
before_action :set_user, only: [:create]
def new
@user = User.new
end
def create
authenticated_user = @user.authenticate(session_params[:password]) if @user
if authenticated_user
session[:id] = @user.id
redirect_to dashboard_path, notice... |
class User < ActiveResource::Base
def full_name
[self.first_name, self.last_name].join(" ")
end
end |
require 'rails_helper'
require 'spec_helper'
RSpec.describe "Movies index page" do
before :each do
mock_user
visit '/'
click_link "Sign in with Google"
click_button "Discover Top 40 Rated Movies"
end
VCR.use_cassette('returns_the_top_rated_movies') do
it "routes to the movie show page proper... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.