text stringlengths 10 2.61M |
|---|
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
include ErrorsFormat
def formated_errors
fill_model_errors(self )
end
end
|
# frozen_string_literal: true
module LightSerializer
class Attributes
def self.prepare(object)
new.prepare(object)
end
# :reek:ManualDispatch
# :reek:FeatureEnvy
def prepare(object)
return object unless object.respond_to?(:to_h)
object.to_h.transform_values(&method(:value_to_h... |
module Bowline
module Desktop
module App
##
# :singleton-method: busy(bool = true)
# Shows a busy cursor (hourglass) on all windows.
##
# :singleton-method: exit
# Exits the application.
end
end
end |
def first_covering_prefix(input)
raise ArgumentError, "input must be an array" unless input.is_a? Enumerable
storage = {}
input.each do |value|
storage[value] = 1
end
size = storage.size
covering_storage = {}
result = 0
input.each_with_index do |value, index|
covering_storage[value]... |
class Advertiser < ActiveRecord::Base
has_many :ads
validates :email, :uniqueness => { :case_sensitive => false }
end
|
# encoding: UTF-8
# Copyright 2012 Twitter, Inc
# http://www.apache.org/licenses/LICENSE-2.0
require 'spec_helper'
describe TwitterCldr::Parsers::UnicodeRegexParser::CharacterSet do
describe "#to_set" do
it "should return a set containing codepoints for the given general property" do
char_set = described... |
Rails.application.routes.draw do
if ENV.fetch('USE_SHIBBOLETH_ONLY') == 'true' # Shibboleth is the only authentication option and all URLs are protected by it
devise_for :identities, :controllers => { :omniauth_callbacks => "identities/omniauth_callbacks" }, :path_names => {:sign_in => 'auth/shibboleth' }
else... |
#!/usr/bin/env ruby
require 'jgrep'
require 'optparse'
options = {:flat => false, :start => nil, :field => []}
begin
OptionParser.new do |opts|
opts.banner = "Usage: jgrep [options] \"expression\""
opts.on("-s", "--simple [FIELDS]", "Display only one or more fields from each of the resulting json... |
class String
def is_i?
!!(self =~ /\A[-+]?[0-9]+\z/)
end
end
class ImagesDrop < Liquid::Drop
def initialize(images)
@images = images
end
def before_method(id_or_name)
if id_or_name.is_a?(String)
if id_or_name.is_i?
find_by_id(id_or_name.to_i)
else
find_by_name(id_or_... |
class TeamsIntegrationsController < ApplicationController
before_action :set_teams_integration, only: [:show, :edit, :update, :destroy]
before_action :authorize
# GET /teams_integrations
def index
@teams_integrations = TeamsIntegration.all
end
# GET /teams_integrations/1
def show
end
# GET /tea... |
# 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 'journey'
describe Journeys do
let(:liverpool_street) {double :station}
let(:farringdon) {double :station}
describe '#entry_station' do
it 'should return the entry station' do
subject.entry_station = liverpool_street
expect(subject.entry_station).to eq(liverpool_street)
end
end
... |
taxonomy = Spree::Taxonomy.first
taxonomy.root.children.each do |taxon|
puts ':' * 100
puts "Uploading product images for: #{taxonomy.name} > #{taxon.name}"
puts ':' * 100
filedir = taxon.name
image_files = Dir["data/#{filedir}/*.jpg", "data/#{filedir}/*.jpeg"]
next if image_files.blank?
image_files.sh... |
require 'paysafe/result'
module Paysafe
class Verification < Result
attributes :id, :merchant_ref_num, :child_account_num,
:auth_code, :customer_ip, :dup_check, :description, :txn_time,
:currency_code, :avs_response, :cvv_verification, :status
object_attribute :Profile, :profile
object_attri... |
# create 'full' array with every integer
# compare that array with array provided as argument
# - have empty results array
# - << element if element in full array is NOT included in provided array
# return results array
def missing(array)
result = []
full = (array.first..array.last).to_a
full.each do |num... |
# frozen_string_literal: true
module Api
module Overrides
# Restriction in login for fos in web and manager in mobile
class SessionsController < DeviseTokenAuth::SessionsController
def create
super { send("#{request_agent}_login") }
end
private
# Allow only login in mobile d... |
FactoryGirl.define do
# Crea topicos genericos
factory :task do
sequence(:code) { |n| "T#{n *10}" }
sequence(:title) { |n| "Task #{n *10}" }
sequence(:sequence) {|n| n * 10 }
rroute ""
description "description"
general true
active true
end
end |
require "rails/generators/erb/mailer/mailer_generator"
module Mjml
module Generators
class MailerGenerator < Erb::Generators::MailerGenerator
source_root File.expand_path("../templates", __FILE__)
protected
def format
nil # Our templates have no format
end
def formats
... |
require 'test_helper'
class TestImage < Minitest::Test
def setup
@image = Pietr::Image.new("assets/euclid_clint.png")
end
def test_init
assert @image
end
def test_width
assert_equal(@image.width, 10)
end
def test_height
assert_equal(@image.height, 10)
end
def test_xy_color
ass... |
# frozen_string_literal: true
require 'sinatra/base'
require 'jiji/web/services/abstract_service'
module Jiji::Web::Test
class MailService < Jiji::Web::AuthenticationRequiredService
options '/' do
allow('GET,OPTIONS')
end
get '/' do
deliveries = Mail::TestMailer.deliveries.map do |mail|
... |
class AwardCeremony
attr_reader :name, :event_date
attr_writer :tickets
def initialize(args = {})
@name = args[:name]
@event_date = args[:event_date]
end
def tickets
@tickets ||= []
end
def take_ticket
tickets.pop
end
def tickets_left
tickets.length
end
def sold_out?
t... |
class AddIndexToItemUse < ActiveRecord::Migration[5.2]
def change
add_index :item_uses, [:e_no, :result_no, :generate_no], :unique => false, :name => 'resultno_and_eno'
add_index :item_uses, :i_no
add_index :item_uses, :name
end
end
|
class User < ApplicationRecord
has_one :game_master, dependent: :destroy
has_many :games
has_many :user_roles, dependent: :destroy
has_many :characters, dependent: :destroy
mount_uploader :avatar, AvatarUploader
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutab... |
require_relative 'spec_helper'
require 'bowler/dsl'
module Bowler
describe DSL do
include DefinitionHelper
context "given a valid pinfile" do
it "should return a valid definition" do
path_to_pinfile = File.join( File.dirname(__FILE__), 'fixtures', 'dsl_valid_pinfile' )
definition = D... |
Castle::Application.routes.draw do
# Admin Login/Logout Paths
match "admin-login" => "admin_sessions#check_session", as: :admin_login
match "admin-logout" => "admin_sessions#destroy", as: :admin_logout
match "admin-dashboard" => "admins#admin_dashboard", as: :admin_dashboard
# Admin Login/Logout Paths
mat... |
# 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... |
class Artist < ApplicationRecord
has_many :albums, dependent: :destroy
validates_presence_of :name
validates_uniqueness_of :name
def number_of_albums
Album.where(artist_id: self.id).count
end
def range_of_years
years = Album.select('year').where(artist_id: self.id)
case years.length
when 0... |
# Base model's class
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
end
|
class AddControllerAndActionToItem < ActiveRecord::Migration
def self.up
add_column :items, :controller, :string, :null => false, :default => 'homes', :limit => 64
add_column :items, :action, :string, :null => false, :default => 'index', :limit => 32
remove_column :items, :url
end
def self.down
r... |
Sequel.migration do
up do
add_column :work_queue, :status, String
add_column :work_queue, :log, String
add_column :work_queue, :created, String
add_column :work_queue, :run_at, String
add_column :work_queue, :started, String
add_column :work_queue, :finished, String
t = Time.at(0)
fr... |
# frozen_string_literal: true
class Suggestion < Sequel::Model
plugin :timestamps, create: :created, update: :updated, update_on_create: true
include Rogare::Utilities
many_to_one :author, class: :User, key: :user_id
end
|
class Api::OrdersController < Api::ApiController
expose :order, id: ->{ params[:slug] }, scope: ->{ @active_company.orders.includes_associated }, find_by: :slug
# POST /api/orders
def create
order.company = @active_company
if order.save
render json: order.render, status: 201
else
render ... |
module CDI
module V1
class HomeForMultiplierSerializer < SimpleHomeSerializer
attributes :learning_tracks_reports
has_many :recent_library_items, serializer: LibrarySerializer
has_many :learning_tracks_recommendations, serializer: LearningTrackHomeSerializer
end
end
end
|
class Guests::DashboardController < ApplicationController
before_filter :require_guest_or_token
layout "guests"
def show
@client_versions = ClientVersion.paginate :page => params[:page], :per_page => 10, :order => "release_date DESC"
end
private
def require_guest_or_token
require_guest if l... |
class Show
attr_reader :name,
:creator,
:characters
def initialize(name, creator, characters)
@name = name
@creator = creator
@characters = characters
end
def total_salary
total_amount = 0
@characters.each do |character|
total_amount += character.salary
... |
module PagePrintable
extend ActiveSupport::Concern
def page_status
s = "#{page_number}면"
if color_page
s += "(칼라)"
else
s += "(흑백)"
end
s += " 출력: #{print_count}"
s
end
def print_status
s = ""
s += "인쇄 #{print_time}" if print_count > 0
s
end
def proo... |
require 'spec_helper'
class EntryArrayDouble < ::Array
def total
size
end
end
class ClientDouble
def initialize(response = EntryArrayDouble.new)
@response = response
end
def entries(options = {})
@response
end
end
class ExporterDouble
def run; end
end
describe Jekyll::Contentful::Importer... |
class Restaurant < ApplicationRecord
has_many :comments
def to_s
name
end
end
|
require './lib/roadmap'
require './lib/message'
require 'httparty'
require 'json'
class Kele
include HTTParty
include Roadmap
include Message
base_uri 'https://www.bloc.io/api/v1'
def initialize(email, password)
@email = email
@password = password
response = self.class.post("/sessions", body: {... |
class QuestionSerializer
include FastJsonapi::ObjectSerializer
attributes :title
has_many :answers
end
|
Gem::Specification.new do |s|
s.name = 'humble_rpi-plugin-vibrationsensor'
s.version = '0.2.0'
s.summary = 'A Humble RPi plugin which detects vibrations using the vibration sensor (SW-18010P).'
s.authors = ['James Robertson']
s.files = Dir['lib/humble_rpi-plugin-vibrationsensor.rb']
s.add_runtime_dependency... |
class UserSerializer < ActiveModel::Serializer
#embed :ids, include: true
root false
attributes :auth_token, :login_alias, :name
attributes :gender, :require_info, :school
has_one :xrole, key: :role, serializer: RoleSerializer
has_many :roles, each_serializer: RoleSerializer
def gender
object.info.g... |
class CategoriesController < ApplicationController
before_filter :get_post_object, :only =>[:edit, :update,:destroy]
private
def get_post_object
@category=Category.find_by_id(params[:id])
if @category.nil?
flash[:error]="sorry,no category found!"
redirect_to categories_path and return
end
... |
require_dependency 'blacklight/catalog'
require 'rest_client'
class Asset
attr_accessor :druid
attr_accessor :page_number
attr_accessor :asset_repository_connection
def initialize(id, page_number = nil)
@druid = id
@page_number = page_number
@asset_repository_connection = Stanford::AssetR... |
class CreateChamados < ActiveRecord::Migration[6.1]
def change
create_table :chamados do |t|
t.string :descricaoCurta
t.text :descricaoLonga
t.integer :estado
t.date :data_criacao
t.date :inicio_atendimento
t.date :fim_atendimento
t.belongs_to :usuario
t.belongs_to ... |
class CreateTongjiDays < ActiveRecord::Migration
def change
create_table :tongji_days do |t|
t.date :day
t.integer :a1
t.integer :a2
t.integer :a3
t.integer :a4
t.integer :a5
t.integer :a6
t.integer :a7
t.integer :a8
t.integer :a9
t.integer :a10
... |
class WorkingDirectory < Directory
def initialize(path)
super(path)
unless File.directory?(@path)
# begin
Dir.mkdir(@path)
# rescue SystemCallError => e
# end
end
end
def clean!(files_to_leave = [])
files_to_leave = files_to_leave.collect {|f| self.path_of(f)}
... |
class Prof < ApplicationRecord
has_one_attached :avatar
has_many :bookings
#has_many :favorites, :as => :favoritable
#has_many :favorites, as: :favoritable
#:favoritable, polymorphic: true, optional: true, dependent: :destroy
# belongs_to :favorites, as: :favoritable
has_many :slots, :through => :booking... |
class User < ApplicationRecord
validates :fullname, presence: true, length: { maximum: 25 }
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :valid... |
class TeamsController < ApplicationController
def teampanel
end
def new
@team = Team.new
end
def create
name = params[:team][:name]
org = current_user.organization_id
@team = Team.new(name: name, organization_id: org)
if @team.save
current_user.update_attribute(:team_id, @team.id)
current_user.u... |
# frozen_string_literal: true
require 'rototiller'
require_relative 'lib/acceptance/bolt_setup_helper'
# rubocop:disable Style/MixinUsage
extend Acceptance::BoltSetupHelper
# rubocop:enable Style/MixinUsage
desc "Generate Beaker Host config"
rototiller_task :host_config do |task|
unless ENV['BEAKER_HOSTS']
tas... |
# frozen_string_literal: true
lib = File.expand_path('lib', __dir__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'i18n_def_scanner/version'
Gem::Specification.new do |spec|
spec.name = 'i18n_def_scanner'
spec.version = I18nDefScanner::VERSION
spec.authors = ['GeorgeGorb... |
# require modules here
require "yaml"
def load_library(file="./lib/emoticons.yml")
emoticons = YAML.load_file(file)
emoticons_hash = {:get_meaning => {}, :get_emoticon => {}}
emoticons.each do |type, language|
emoticons_hash[:get_meaning][language[1]] = type
emoticons_hash[:get_emoticon][language... |
class CreateMailLogs < ActiveRecord::Migration
def self.up
create_table :mail_logs do |t|
t.string :subject
t.text :body
t.string :type
t.integer :mail_message_id
t.string :sender_mail_id
t.integer :sender_id
t.string :alert_record_type
t.integer :alert_record_id
... |
module Fog
module Compute
class Brkt
class Real
def create_security_group(network_id, name, options = {})
body = Fog::StringifyKeys.stringify(options).merge({:name => name})
request(
:expects => [201],
:method => "POST",
:path => "v1/api/co... |
module ActionController
class Base
alias :rails_redirect_to :redirect_to
alias :rails_render :render
def redirect_to(options = {}, response_status = {})
if options.class == Hash
options.merge!( :layout => 'spakit' ) if ( self.params[:layout].to_s == 'spakit' && !options.include?(:la... |
class AddAttendToIsbiAndAttendToEbcToUsers < ActiveRecord::Migration
def change
add_column :users, :attend_to_isbi, :boolean
add_column :users, :attend_to_ebc, :boolean
end
end
|
require './spec/spec_helper.rb'
describe 'Word Search Test' do
self.use_transactional_fixtures = false
before :all do
ensure_server_is_running
DatabaseCleaner.clean
end
after :all do
DatabaseCleaner.clean
end
describe 'Word Search Test' do
before :all do
@english = Language.creat... |
# frozen_string_literal: true
require "graphql/tracing/platform_trace"
module GraphQL
module Tracing
# This implementation forwards events to a notification handler (i.e.
# ActiveSupport::Notifications or Dry::Monitor::Notifications)
# with a `graphql` suffix.
module NotificationsTrace
# Initi... |
require 'cocoapods'
require 'pathname'
module CocoapodsDependency
#
# Analyze the project using cocoapods
#
class Analyzer
def self.analyze(podfile_dir_path)
path = Pathname.new(podfile_dir_path)
raise 'absolute path is needed' unless path.absolute?
Dir.chdir(podfile_dir_path) do
... |
require 'flip_the_switch/generator/base'
require 'active_support/inflector'
require 'erb'
module FlipTheSwitch
module Generator
class Category < Base
def generate
delete_existing
write_files
end
private
def delete_existing
delete_file(header_file)
delete_... |
require "spec_helper"
describe Api::Public::V2::ArticlesController do
request_params = {
:format => :json
}
render_views
describe "GET show" do
it "finds the object if it exists" do
entry = create :blog_entry
get :show, { obj_key: entry.obj_key }.merge(request_params)
assigns(:artic... |
# frozen_string_literal: true
module Authegy
class Railtie < ::Rails::Railtie
railtie_name :authegy
end
end
|
my_dogs = [
{ :name => 'Ralph', :position => 5 },
{ :name => 'Cindy', :position => 8 },
{ :name => 'Jade', :position => 11 },
]
def get_absent_dogs(dogs)
absent_dogs = []
dog_name = dogs.select{|dog| dog[:position] > 10}
#specifically get the name of the absent dog
dog_name.each do |dog|
absent_dogs... |
FactoryBot.define do
factory :garden_health do
sensor
reading_type { [0, 1].sample }
reading { Faker::Number.decimal(l_digits: 3, r_digits: 3) }
time_of_reading { Faker::Time.between(from: DateTime.now - 1, to: DateTime.now) }
end
end
|
class TheBigBang < ActiveRecord::Migration
def change
create_table "account_budgets", force: :cascade do |t|
t.string "account_id", limit: 191
t.decimal "daily_budget", precision: 8, scale: 2
t.datetime "created_at", null: false
t.date... |
class HomeController < ApplicationController
layout 'application'
def index
@html_title = "Home - "
@maps = Map.where(:status => 4).order(:updated_at => :desc).limit(3).includes(:gcps)
@layers = Layer.all.order(:updated_at => :desc).limit(3).includes(:maps)
@my_maps = @curre... |
# 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... |
class AddNewFieldsToAssessment < ActiveRecord::Migration
def change
add_column :assessments, :event_log, :text
add_column :assessments, :intermediate_results, :text
end
end
|
##
# CacheTasks
#
# An API for caching, and enqueing caching.
# Meant to be run mostly as rake tasks.
#
# Each task should respond to a #run method.
#
module CacheTasks
class Task
include ::NewRelic::Agent::Instrumentation::ControllerInstrumentation
attr_accessor :verbose
def cacher
@cacher ||... |
require_relative 'project'
RSpec.describe Project do
before(:each) do
@project = Project.new('Project', 'Description')
end
it "has a getter and setter for name and description attributes" do
@project.name = "New Name"
@project.description = "New Description"
expect(@project.n... |
=begin
Assumptions made:
Only one book with the same title on a particular library.
A shelf always depends on the library it was created.
=end
#LIBRARY
class Library
attr_accessor :books
def initialize(name)
# Instance variables
@name = name
@shelves = Array.new
@books = Array.new
end
... |
class Submission < ActiveRecord::Base
belongs_to :store, foreign_key: 'store_id', primary_key: 'uid'
attr_encrypted :name, :key => ENV['ENCRYPTION_KEY']
attr_encrypted :email, :key => ENV['ENCRYPTION_KEY']
after_create :invalidate_dashboard
after_create :send_receipt, :unless => :silent
def self.latest
... |
require 'spec_helper'
describe Susanoo::ServerSync::Syncers::Base do
describe "メソッド" do
let(:server) { 'localhost' }
subject { Susanoo::ServerSync::Syncers::Base.new(server) }
it { should respond_to(:src) }
it { should respond_to(:dest) }
it { should respond_to(:user) }
it { should respond_t... |
Pod::Spec.new do |s|
s.name = 'Themed'
s.version = '0.1.0'
s.summary = 'A light weight, simple and flexible theme engine for iOS written in Swift.'
s.description = <<-DESC
Themed is a theme engine for iOS.
+ Write styles in Swift
+ Keep styles DRY
+ Supports runtime style chan... |
class AddOrganizationIdToOrganizationChargeTemplates < ActiveRecord::Migration
def change
add_column :organization_charge_templates, :organization_id, :integer
end
end
|
class AlbumsController < ApplicationController
def index
@albums = Album.all
render :index
end
def new
@album = Album.new
render :new
end
def create
@album = Album.new(album_params)
if @album.save
flash[:notice] = "Now thats motherfucking album!"
redirect_to albums_path... |
class AddArtistToSongs < ActiveRecord::Migration[4.2]
add_column :song_id, :artist_id, :genre_id
end
|
FactoryGirl.define do
factory :menu_item do
name {
("#{Faker::App.name} #{['taco', 'torta', 'burrito', 'huevos rancheros', 'horchata'].sample}")
}
price { [1.50, 3.00, 2.50, 3.00, 1.00, 1.75, 2.00, 2.45, 3.40, 2.15].sample }
factory :invalid_menu_item do
name nil
price nil
end
... |
# frozen_string_literal: true
describe Kafka::Compressor do
describe ".compress" do
let(:instrumenter) { Kafka::Instrumenter.new(client_id: "test") }
context 'legacy message set' do
it "only compresses the messages if there are at least the configured threshold" do
compressor = Kafka::Compress... |
class AddDocumentToAssignments < ActiveRecord::Migration
def change
add_attachment :assignments, :document
end
end
|
class Tweet < ActiveRecord::Base
hobo_model # Don't put anything above this
# require 'rubygems'
# require TLD
fields do
text :string
contact_id :integer
timestamps
end
belongs_to :contact
### Could not get gem tld to load! :(
def text_parse_links
text.gsub(/((\w+\.){1,3}\w... |
module ApplicationHelper
# Returns the full title on a per-page basis.
def full_title(page_title = '')
base_title = BEARS['app_name']
if page_title.empty?
base_title
else
page_title + " | " + base_title
end
end
# returns proper wrapper id for
def wrapper_id
logged_in? ? "pag... |
class Category < ActiveRecord::Base
has_many :links, dependent: :destroy
has_many :products, through: :links
validates :name, presence: true
end
|
require 'spec_helper'
describe Communique::Handler do
describe '#external_services' do
context 'no config block' do
it 'works with no config block' do
expect(Communique::Handler)
.to receive(:external_services)
.and_return nil
dummy = NotifiableDummy.create
Commu... |
# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.
class ApplicationController < ActionController::Base
helper :all # include all helpers, all the time
#protect_from_forgery # See ActionController::RequestForgeryP... |
class RenameEventsTypeColumnToEventType < ActiveRecord::Migration
def self.up
change_table :events do |t|
t.rename :type, :event_type
end
end
def self.down
change_table :events do |t|
t.rename :event_type, :type
end
end
end
|
require "spec_helper"
RSpec.describe "Day 25: Let It Snow" do
let(:runner) { Runner.new("2015/25") }
describe "Part One" do
let(:solution) { runner.execute!(input, part: 1) }
it "finds the code for any given position" do
expect(runner.execute!("row 1, column 1", part: 1)).to eq(20_151_125)
ex... |
# encoding: utf-8
class ReportGenerators::MonitoringReport < ReportGenerators::Base
def self.can_process? type
type == Monitoring
end
def add_to(document)
if !is_empty? && !themes.first.monitoring_data.empty?
add_information_to document
end
end
private
def is_empty?
themes.empty? &... |
class Fat < ActiveRecord::Base
def self.ave_on(date)
where("date(purchased_at) = ?", date).sum(:fat)
end
end
|
# frozen_string_literal: true
module TestProf
# Add ability to run only a specified number of example groups (randomly selected)
module MinitestSample
# Do not add these classes to resulted sample
CORE_RUNNABLES = [
Minitest::Test,
Minitest::Unit::TestCase,
Minitest::Spec
].freeze
... |
class BTreeSort
def initialize
@output = []
end
class BinaryTree
attr_accessor :payload, :left, :right
def initialize(payload)
@payload = payload
end
end
def compare(num, node)
return BinaryTree.new(num) if node.nil?
if num < node.payload
node.left = compar... |
# Write a method that takes a String of digits, and returns the appropriate number as an integer. The String may have a leading + or - sign; if the first character is a +, your method should return a positive number; if it is a -, your method should return a negative number. If no sign is given, you should return a po... |
require 'rails_helper'
RSpec.describe Sword::Metadata::ModsName do
context "API/interface" do
it 'has #name_part attr_accessor' do
expect(subject).to respond_to(:name_part)
expect(subject).to respond_to(:name_part=)
end
it 'has #id attr_accessor' do
expect(subject).to respond_to(:i... |
class Image < ApplicationRecord
include Filterable
include Tagable # includes relationsships and tags-scope
mount_uploader(:file, ImageUploader)
validates :file, presence: true
has_many :posts
has_many :pages
def to_s
title || file_name
end
def url
file.large.url
end
def thumb_url
... |
class AddIndexOrganizationsCity < ActiveRecord::Migration
def change
def change
add_index :organizations, :city, unique: true
end
end
end
|
module Movable
extend ActiveSupport::Concern
def move_to_agent(agent_destination)
aliasable_name = ActiveModel::Naming.plural(self.class)
if agent_destination.nil?
errors.add(:agent, I18n.t('errors.' + aliasable_name + '.move_to_unknown_agent'))
return false
end
if Feature.quota_enabl... |
require 'spec_helper'
require './spec/helpers/message_helper'
require 'tempfile'
RSpec.configure do |c|
c.include Helpers::MessageHelper
end
RSpec.describe Paubox::Message do
describe '#build_parts' do
it 'builds headers' do
message = Paubox::Message.new(message_with_attachment_args)
tested_keys =... |
@follows.each do |follow|
json.set! follow.id do
json.extract! follow, :id, :series_id, :user_id
json.series do
json.id follow.series.id
json.title follow.series.title
json.description follow.series.description
json.thumbnail_url follow.series.thumbnail_url
json.year follow.serie... |
class Comment < ActiveRecord::Base
after_save :notify_new_comment
def notify_new_comment
redis = Redis.new
redis.publish("new_comment", {:title => self.title, :content => self.content}.to_json)
end
end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.