text stringlengths 10 2.61M |
|---|
require 'spec_helper'
class Transaction
attr_accessor :transaction_number, :amount
attr_reader :save
def initialize(amount)
@amount = amount
end
def update_attribute(field, value)
send("#{field}=", value)
end
def new_record?
true
end
def transaction_number
'1442772645'
end
end
... |
# @author: Houman Kargaran - 2017
# Defining Object
class Tulip
# Defining an array of hashes to define the content of this product
#
# @param
# @return [Array<Hash>] product details
def self.packs
[
{ :pack => 3, :price => 5.95 },
{ :pack => 5, :price => 9.95 },
... |
require 'rails_helper'
RSpec.describe CartItem, type: :model do
context "#associations" do
it {should belong_to :cart}
it {should belong_to :item}
end
end
|
require 'spec_helper'
describe 'Collections overlay', :reset => false do
before(:all) do
Capybara.reset_sessions!
load_page :search
end
after(:each) do
reset_overlay
reset_project
end
it "shows collection details when clicking on a collection" do
expect(page).to have_visible_collection_... |
require 'rails_helper'
RSpec.describe Currency, type: :model do
it 'has a valid factory' do
expect(FactoryGirl.create(:currency)).to be_valid
end
it { is_expected.to validate_presence_of(:iso_code) }
it { is_expected.to validate_presence_of(:rate) }
before do
@existing_currencies = FactoryGirl.cre... |
class FightsController < ApplicationController
before_action :setup_fight, only: :show
def show
end
def create
player_id = current_user.current_player.id
fight = FightAlgorithm.new(player_id, Monster.find(params[:monster_id]).id).call
fight_history = Fight.create(player_id: player_id, exp: ... |
class ModeOfDelivery < ActiveRecord::Base
self.table_name = :mode_of_delivery
self.primary_key = :mode_of_delivery_id
include EbrsMetadata
has_many :person_birth_details, foreign_key: "mode_of_delivery_id"
end
|
module API
module V1
class ResourcesFeatured < API::V1::Base
before do
authenticate_user
end
ResourceFeatured::VALID_RESOURCES_TYPES.keys.each do |key|
namespace key do
route_param :id do
namespace :featured do
desc 'Mark a given resource as... |
class Network
attr_reader :name,
:shows
def initialize(name)
@name = name
@shows = []
end
def add_show(show)
@shows.push(show)
end
def main_characters
main = []
shows.each do |show|
show.characters.each do |character|
if character.name == character.name.upc... |
# frozen_string_literal: true
class SessionsController < ApplicationController
skip_before_action :verify_login
def login
redirect_to books_path if current_user
end
def create
user = User.find_by(email: params[:session][:email].downcase)
if user&.authenticate(params[:session][:password])
log... |
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
http_basic_authenticate_with name: ENV['API_USERNAME'], password: ENV['API_PASSWORD']
def home
end
def fetch_q... |
class Merchant < ActiveRecord::Base
has_many :invoices
has_many :items
has_many :customers, through: :invoices
validates :name, presence: true
def self.most_revenue(quantity)
all.sort_by{ |merchant| merchant.total_revenue }.last(quantity).reverse
# Merchant.all.sort_by {|merchant| merchant.revenue }... |
class PassengerTrain < Train
def initialize(number)
@train_type = 'пассажирский'
super
end
end
|
class CommonError
attr_accessor :messages
def initialize
@messages = []
end
def <<(msg)
@messages << msg
end
def valid?
@messages.blank?
end
def full_messages
@messages
end
def count
@messages.length
end
end
|
class CreateSeasons < ActiveRecord::Migration
def change
create_table :seasons do |t|
t.integer :series_id, references: :series, on_update: :cascade, on_delete: :cascade
t.integer :number
t.timestamps
end
end
end
|
class Tag < ActiveRecord::Base
has_and_belongs_to_many :creatives
def self.like(str)
where("value LIKE ? ", "%#{str}%").order(:ammount).take(10)
end
def self.most_popular
order(:ammount => :desc).take(10)
end
def self.get_or_create(tag_value)
tag = where(:value => tag_value).last
if t... |
module ContactsInteractor
# Context parameters
# importer: kind of ContactImporter
# content: string
class ImportWithString
include Interactor
def call
@importer = context.importer.new(context.content)
@importer.import
context.total = @importer.total
context.imported = @importe... |
class User < ActiveRecord::Base
attr_accessible :email, :name
has_many :blogs
validates_presence_of :name
validates_presence_of :email
end
|
# The module is rails helper for displaying a calendar
# list view. It requires a collection of event objects
# passed in, as well as the date requested.
# The event objects are expected to have fields of
# * title : string
# * location : string
# * start : datetime
# * end :datetime
# * all_day : boolean
# * no... |
# frozen_string_literal: true
RSpec.describe "pattern matching" do
context "Result" do
include Dry::Monads[:result, :maybe]
context "Success" do
let(:match) { Test::Context.new }
let(:hash_like) do
Object.new.tap do |o|
def o.deconstruct_keys(_)
{code: 101}
... |
require 'test_helper'
module JackCompiler
module Transformer
module SymbolTableTestHelper
def self.with_new_table(class_name: nil, &block)
symbol_table = JackCompiler::Transformer::SymbolTable.new
if class_name
symbol_table.instance_eval do
@class_name = class_name
... |
# -*- coding: utf-8 -*-
require 'spec_helper'
shared_examples_for "an adapter" do
describe "create procedure migration" do
create_procedure_migration = Class.new(ActiveRecord::Migration) do
def change
create_procedure :test_procedure, language: 'plpgsql', returns: 'text', sql: <<-SQL
RETURN... |
# == Schema Information
#
# Table name: players
#
# id :integer not null, primary key
# first_name :string
# last_name :string
# birthday :datetime
# height :string
# weight :string
# shoots :string
# position :string
# city :string
# state :string
# country :s... |
require_relative "./indexer"
require_relative "./parser"
module RecommendedLinks
class IndexingTask
attr_reader :data_path, :indexer
def initialize(data_path, options = {})
@data_path = data_path
@indexer = options[:indexer]
end
def run
if indexer
indexer.index(recommended... |
# typed: false
# frozen_string_literal: true
# Documentation: https://docs.brew.sh/Formula-Cookbook
# https://rubydoc.brew.sh/Formula
# PLEASE REMOVE ALL GENERATED COMMENTS BEFORE SUBMITTING YOUR PULL REQUEST!
class Fcitx < Formula
desc ""
homepage ""
url "https://github.com/fcitx/fcitx.git"
ver... |
module Sword
module Metadata
class Degree
attr_accessor :discipline,
:grantor,
:level,
:name
end
end
end
|
module DynaStruct
class Full
def initialize(args=nil)
args.each_pair do |k, v|
instance_variable_set("@#{k}", v)
add_attribute(k)
end if args.kind_of?(Hash)
end
def [](name)
instance_variable_get("@#{name}")
end
def []=(name, value)
instance_variable_set("... |
require 'spec_helper'
describe PaginationCell, type: :cell do
context 'cell rendering' do
context 'rendering show' do
subject { render_cell(:pagination, :show) }
it { is_expected.to have_selector('h1', text: 'Pagination#show') }
it { is_expected.to have_selector('p', text: 'Find me in app/cel... |
require 'rest-client'
require 'json'
require 'pry'
URL = "http://www.swapi.co/api/"
def get_about_from_api(about, name, info)
about_hash = nil
loop do
if about_hash == nil
about_hash = parse_json(URL+"#{about}/")
else
about_hash = parse_json(about_hash['next'])
end
about_hash["results... |
#!/usr/bin/env ruby
require 'json'
require 'open3'
class LD
def initialize(i)
@opcode = i['opcode']
@mnemonic, @cycles = i['implementation'].values_at('mnemonic', 'cycles')
end
def load_value
case @mnemonic
when /,\((a8|C)\)$/ # Zero page
"value := cpu.memory.Read(mmu.ZeroPage.AddressOf(c... |
require 'user_class'
describe User do
describe '.all' do
it '.all method exists' do
expect(User).to respond_to(:all)
end
it 'returns all usernames' do
add_row_to_users_test_database
connection = PG.connect(dbname: 'makersbnb_test')
expect(User.all[0].username).to eq "Joe"
ex... |
require 'rails_helper'
describe "user sees all categories" do
before :each do
@category1 = Category.create!(name: 'cats', description: 'cat things')
@category2 = Category.create(name: 'fish', description: 'trout')
end
scenario "all categories are shown" do
visit categories_path
expect(page).to ... |
# Helper class for constructing authentication headers required by the Game Server APIs
# This class relies on two config variables: gameserver.admin_api_token, and gameserver.admin_shared_secret
module GameServer
module AuthenticationHelper
# Construct a Hash of authentication headers required by the Client AP... |
class Location < ActiveRecord::Base
has_and_belongs_to_many :specialties
validates :name, presence: true
validates :address, presence: true
def self.default_scope
includes(:specialties)
end
scope :approved, -> { where(approved: true) }
scope :unapproved, -> { where(approved: false) }
geocoded_by ... |
########################################################
# Step 1: Establish the layers
# In this section of the file, as a series of comments, create a list of the layers you identify.
# There are three layers: all data for all rides, data for drivers, and data for rides
# Things: driver id, rider id, cost,... |
def is_prime?(num)
if ! num.kind_of?(Integer) || num <= 1
raise
elsif [2, 3, 5, 7].include?(num)
true
elsif num.even?
false
else
sqrt = (num**0.5).ceil
flag = true
3.step(sqrt, 2).each do |d|
if num % d == 0
flag = false
break
end
end
flag
end
end
n... |
class AddNameToRooms < ActiveRecord::Migration[5.0]
def change
add_column :rooms,:name,:string,null: false
end
end
|
class CartsController < ApplicationController
include ApplicationHelper
include Rectify::ControllerHelpers
def index
@coupon_form = Coupon.new
end
def create
AddToCart.call(current_order, params) do
on(:valid) do |quantity|
flash[:notice] = t('flash.success.book_add', count: quanti... |
class Album < ActiveRecord::Base
attr_accessible :title
validates :title, :presence => true
has_many :songs, :dependent => :destroy
belongs_to :artist
end
|
class Student::CoursewaresController < ApplicationController
layout 'student'
before_filter :get_student_and_course
# GET /student/courses/1/coursewares
# GET /student/courses/1/coursewares.json
def index
@coursewares = Courseware.where(:course_id => @course.id).order('created_at DESC').page(params[:page]... |
# frozen_string_literal: true
class ProviderSerializer < ActiveModel::Serializer
type 'cc_provider'
def id
if Flipper.enabled?(:facility_locator_ppms_forced_unique_id)
obj_id = object.ProviderHexdigest || object.ProviderIdentifier
"ccp_#{obj_id}"
else
"ccp_#{object.ProviderIdentifier}"
... |
module PointlessFeedback
class FeedbackMailer < ActionMailer::Base
def feedback(message)
@message = message
mail(:to => to_emails, :subject => feedback_subject, :from => from_address)
end
private
def from_address
if PointlessFeedback.send_from_submitter
@message.email_addr... |
# Source: https://launchschool.com/exercises/7fe5eaf8
# Write a method that takes the lengths of the 3 sides of a triangle as
# arguments, and returns a symbol :equilateral, :isosceles, :scalene, or
# :invalid depending on whether the triangle is equilateral, isosceles,
# scalene, or invalid.
def triangle(a, b, c)
... |
class EpicList < ApplicationRecord
validates :name, presence: true
has_many :epic_lists_epics
has_many :epics, through: :epic_lists_epics
end
|
Website::Application.routes.draw do
root 'static_pages#home'
match '/about', to: 'static_pages#about', via: 'get'
match '/projects', to: 'static_pages#projects', via: 'get'
match '/projects/barbot', to: 'projects#barbot', as: 'barbot', via: 'get'
match '/projects/underactuation', to: 'proje... |
require 'spec_helper'
describe 'wicoris::client' do
let(:chef_run) { ChefSpec::Runner.new }
let(:cache_dir) { Chef::Config[:file_cache_path] }
before do
chef_run.node.set[:wicoris][:client][:filemaker_source] =
'http://example.com/filemaker.dmg'
chef_run.node.set[:wicoris][:client][:filemaker_che... |
require "deck.rb"
describe "Deck" do
describe "#initialize" do
deck = Deck.new
it "should initialize an empty array to be filled" do
expect(deck.cards).to eq([])
end
end
describe "#fill_cards" do
deck = Deck.new
deck.fill_cards
it "should fill the deck with all cards except jokers"... |
require 'cxbrank/const'
require 'cxbrank/master/music'
require 'cxbrank/master/course'
require 'cxbrank/skill'
require 'cxbrank/playdata/music_skill'
require 'cxbrank/playdata/course_skill'
module CxbRank
module PlayData
class << self
def registered app
app.helpers do
def skill_list_page(... |
class ItemsController < ApplicationController
before_action :set_item, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!
load_and_authorize_resource
def create
@patient = Patient.find(params[:item][:patient_id])
@item = @patient.items.new(item_params)
if @item.save!
f... |
require 'test_helper'
class AlipayTest < Minitest::Test
def test_that_it_has_a_version_number
refute_nil ::Alipay::VERSION
end
def test_sign_type_default
assert_equal 'RSA', Alipay.sign_type
end
end
|
# Exercises
# Time estimate: 1.5hrs
# Loop through all the numbers, stopping when you
# encounter a number that is (a) >250 and (b)
# divisible by 7. Print this number down!
=begin
start_num = 0
while true
if start_num > 250 && start_num % 7 == 0
p start_num
exit
end
start_num += 1
end
=end
# Print o... |
require 'test_helper'
class ClientCoursesControllerTest < ActionController::TestCase
setup do
@client_course = client_courses(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:client_courses)
end
test "should get new" do
get :new
assert... |
# Represents the Google Apps service.
module GoogleApps
ENDPOINT = 'https://apps-apis.google.com/a/feeds'
@@backend = Read
@@connection = nil
@@connection_params = { }
# Get the backend used for new connections.
def self.backend
@@backend
end
# Set the backend.
def self.backend=(backen... |
class SubcategoriesController < ApplicationController
before_action :only_admin
before_action :set_subcategory, only: [:edit, :update]
before_action :din_id, only: [:delete_subcategory]
layout "account"
def new
@subcategory = Subcategory.new
@categories = Category.all.order('name')
@subcategories = Sub... |
prawn_document(:page_layout => :portrait) do |pdf|
pdf.move_down 10
pdf.font_size 25
pdf.text 'Expenses'
pdf.move_down 10
expenses = @expenses.map do |expense|
[
expense.expense_category.name,
expense.amount,
expense.date.strftime('%d-%b-%y'),
expense.creater.name
]
end
expenses.un... |
require_relative '../src/coffee'
require_relative '../src/milk'
class Drink
def getDrinkMessage(juiceName)
@juiceName = juiceName
case @juiceName
when 'coffee'
result = Coffee.new.taste
when 'milk'
result = Milk.new.taste
else
result = Drink.new.taste
end
r... |
module Axon
module ScalerTests
def test_dimensions
[
[7, 8],
[71, 82],
[@image.width, @image.height],
[1, 1]
].each do |dims|
im = Solid.new(100, 200)
w, h = dims[0], dims[1]
s = @scalerclass.new(im, w, h)
assert_image_dimensions(s, w, ... |
require 'net/http'
require 'json'
class WorkatoAPI
HOST = 'https://www.workato.com'.freeze
def initialize(email, api_key)
@email = email
@api_key = api_key
end
def folders(parent_id = nil)
uri = URI("#{HOST}/api/folders")
uri.query = URI.encode_www_form(parent_id: parent_id) if parent_id
... |
# -*- encoding: utf-8 -*-
Gem::Specification.new do |gem|
gem.name = "shoperb-theme-editor"
gem.version = "0.7.7"
gem.authors = ["Rainer Sai"]
gem.email = ["rainer.sai@perfectline.co"]
gem.summary = %q{shoperb_theme_editor is a theme manager for Shoperb}
gem.homepage = "http://www.shoperb.c... |
# frozen_string_literal: true
class MemoizeUntil
class Store
attr_reader :_store, :_kind, :_mutex
def initialize(kind)
@_store = {}
@_kind = kind
@_mutex = Mutex.new
end
# returns the value from memory if already memoized for "now" for the given key
# else evaluates the block ... |
if ENV['COVERAGE']
require 'simplecov'
SimpleCov.command_name "rails-tests"
end
if ENV['RETRY']
require 'minitest/retry'
Minitest::Retry.use!
end
ENV['RAILS_ENV'] ||= 'test'
require_relative '../config/environment'
require 'rails/test_help'
if ENV['COVERAGE']
ci_project_dir = ENV.fetch('CI_PROJECT_DIR', nil)... |
class AddIndexToZipcode < ActiveRecord::Migration[5.0]
def change
add_index :zipcodes, :zip_code
end
end
|
class Staff < ApplicationRecord
has_secure_password
EMAIL_REGEX = /\A[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}\Z/i
validates :first_name, :presence => true, :length => { :maximum => 25 }
validates :last_name, :presence => true, :length => { :maximum => 30 }
validates :username, :length => { :within => 8..40 }, :u... |
# == Account role
#
# Describe behaviour of User in application
#
# Used by User
#
module Account
# Returns a string for use as a Gitolite user identifier
#
# Note that Gitolite 2.x requires the following pattern for users:
#
# ^@?[0-9a-zA-Z][0-9a-zA-Z._\@+-]*$
def identifier
# Replace non-word chars ... |
require 'csv'
module CloudCapacitor
module Executors
class DummyExecutor
include Log
def initialize
# nested hash initialization
# Thanks to Anand Immannavar
# http://anandimmannavar.wordpress.com/2013/05/06/ruby-nested-hash-initialization/
@result_for = Hash.new... |
require 'test_helper'
class AcountHistoriesControllerTest < ActionController::TestCase
setup do
@acount_history = acount_histories(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:acount_histories)
end
test "should get new" do
get :new
... |
class UsersController < ApplicationController
before_action :ensure_logged_in, :ensure_current_user, only: [:show]
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
login!(@user)
render js: "window.location = '/'"
else
render json: { error: @u... |
class Task < ActiveRecord::Base
has_one :story
has_one :student
has_many :workdetails
validates :descripcion, :presence => true, :length => {
:minimum => 6,
:message => :too_short
}
validates :estimadoinicial, :numericality => true, :numericality => {:greater_than => 0}, :on => :creat... |
class Computacenter::TechSource
def supplier_outages
SupplierOutage.all # for now Computacenter's TechSource is the only supplier
end
def url
Settings.computacenter.techsource_url
end
def available?
!SupplierOutage.current.exists?
end
def current_supplier_outage
outages = SupplierOutage... |
require "http"
class OpenAI
URI = "https://api.openai.com/v1"
def initialize(api_key:)
@api_key = api_key
end
def completion(prompt:, max_tokens: 64, temperature: 1.0, stop: "<|endoftext|>")
response = HTTP.headers(headers).post(
"#{URI}/engines/davinci/completions",
json: {
promp... |
class Person
attr_reader :name :age, :sex, :email
def initialize(name)
@name = name
@age = age
@sex = sex
@email = email
end
end
p = Person.new('Dayana', 12, 'Male', 'text@email.com')
puts p.name
puts p.age
puts p.sex
puts p.email |
# -------------------------------------------------------------------------- #
# Copyright 2002-2013, OpenNebula Project (OpenNebula.org), C12G Labs #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); you may #
# no... |
Vagrant.configure("2") do |config|
config.vm.box = "ubuntu/bionic64"
config.vm.network "public_network"
#
# Run Ansible from the Vagrant Host
#
config.vm.provision "ansible" do |ansible|
ansible.playbook = "playbook.yml"
ansible.become = true
ansible.vault_password_file = "./vault"
end
end
|
class JoinsController < ApplicationController
def create
@event = Event.find(params[:id])
@join = Join.new(user: current_user, event: @event)
if @join.save
flash[:notice] = ["You have joined to attend to this event!"]
redirect_to events_path
else
flash[:errors] = @join.errors.full_me... |
require 'rails_helper'
describe User, type: :model do
let(:user) do
User.new( name: "Robert",
nickname: "alchemist5280",
token: "mytoken")
end
it 'exists' do
expect(user).to be_valid
end
it 'is invalid without a name' do
user.name = nil
expect(user).not_to be_val... |
class Teacher::ContestRegSerializer < ActiveModel::Serializer
root false
attributes :id, :exdate, :extime
has_one :ugroup, serializer: Teacher::UgroupSerializer
has_one :contest, serializer: Teacher::ContestSerializer
def exdate
object.exdate.strftime("%Y/%m/%d")
end
end
|
require File.expand_path('../boot', __FILE__)
require 'rails/all'
if defined?(Bundler)
# If you precompile assets before deploying to production, use this line
Bundler.require *Rails.groups(:assets => %w(development test))
# If you want your assets lazily compiled in production, use this line
# Bundler.requi... |
#!/usr/bin/env ruby
# in: URL of index page on cmdline
# out: URLs of all index pages in that forum/"Beitragsübersicht" on stdout,
# one URL per line
require 'nokogiri'
url = ARGV[0] or raise "usage: #{$0} <url>"
page = Nokogiri::HTML(IO.popen("wget-withbrowsersettings -q -O- '#{url}'"))
spans = page.css('span'... |
require 'open-uri'
module ApplicationHelper
def MoltinRequest path, method, data = {}, auth = false
uri = URI ENV['MOLTIN_BASE_URL'].dup << path
uri = URI 'https://api.moltin.com' << path if auth
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
headers = {
... |
###Collections Practice
collection_array = ["blake", "ashley", "scott"]
#1. sort the following array in ascending order
collection_array.sort
#2. sort the following array in descending order
collection_array.sort.{|n1,n2| n2<=>n1}
collection_array.sort.{|a,z| z<=>a}
#3. put the following array in reverse orde... |
class ImageMaker
# hold the varibles
attr_accessor :with, :height, :pixel_maps
# If we don't specify the size, start with 0
def initialize(with = 0, height = 0)
@with = with.to_i
@height = height.to_i
draw_image
end
# create a new image
def draw_image
@pixel_maps = (1..@height).map{ (1..... |
class OmniauthCallbacksController < Devise::OmniauthCallbacksController
protect_from_forgery :except => [:twitter,:facebook,:steam]
def twitter
logger.debug "Called twitter callback"
auth = request.env['omniauth.auth']
params = request.env['omniauth.params']
@user = User.find_by_t... |
class AddMaterialToCotizclomuls < ActiveRecord::Migration[5.1]
def change
add_column :cotizclomuls, :material, :string
end
end
|
require 'test_helper'
class JobTest < ActiveSupport::TestCase
def setup
@job = Job.new(job_title: "My New Home Job", job_description: "This is my first home job",
job_address: "123 Sample Street")
end
test "job should be valid" do
assert @job.valid?
end
e... |
require 'rails_helper'
RSpec.describe ImageController, type: :controller do
let(:user) { double("User") }
before do
allow(subject).to receive(:current_user).and_return(user)
end
describe "GET #new" do
it "returns http success" do
get :new
expect(response).to have_http_status(:success)
... |
require './gol.rb'
#require 'pry'
describe Point do
before :each do
@p = Point.new(5, 5)
end
end
describe Cell do
before :each do
@world = World.new(80,60)
@cell = Cell.new(5,5, @world)
end
it "should have no neighbors if it isn't touching any cells" do
@cell.neighbors.should == []
... |
class UsersController < ApplicationUsersController
before_action :set_company, only: %i[index new]
def index
@users = User.where(company_id: current_user.company_id)
end
def new
@user = User.new
end
def create
if User.find_by(email: params[:email])
else
User.create(params.require(:us... |
class ItemSerializer < ActiveModel::Serializer
attributes :id, :body, :list_id, :completed
end
|
class CounterRecordWrapper < BinData::Record
endian :big
bit20 :smi_entity
bit12 :sflow_format
uint32 :counter_record_length
choice :counter_info, :selection => :sflow_format do
if_counters 1
ethernet_counters 2
tokenring_counters 3
vg_counters 4
... |
module AdminListHelper
def display_link(link)
link_to content_tag(:i, nil, class: "icon-share-alt"), link, class: "btn"
end
#-------------
# Associations
# For a polymorphic content association - requires headline and obj_key
def display_content(content)
if content && content.respond_to?(:headline... |
class JoinBetweenRolesAndUsers < ActiveRecord::Migration
def change
create_join_table :roles, :users
change_table :roles do |t|
t.remove :user_id
end
end
end
|
#
# SessionConfig.rb
#
# Created by Martin Hawkins on 2011-02-03.
# Copyright (c) 2011 Topfunky Corporation. All rights reserved.
#
class SessionConfig
attr_accessor :editorName
def initialize(editorName)
@editorName = editorName
end
end |
class Ski < ApplicationRecord
validates :name, presence: true
validates :description, presence: true
validates :brand, presence: true
validates :category, presence: true
validates :price, presence: true
validates :url, presence: true
validates :photo_url, presence: true
end
|
class Partner
class ListAlbumSerializer < ActiveModel::Serializer
include Rails.application.routes.url_helpers
attributes :albums, :links
def albums
ActiveModelSerializers::SerializableResource.new(
object[:albums], each_serializer: Partner::AlbumSerializer
)
end
def links
... |
#At the top of your file, add a method that takes an array and an item as parameters, and returns the array with the item added. So add_to_array([], "a") would return ["a"], and add_to_array(["a", "b", "c", 1, 2], 3) would return ["a", "b", "c", 1, 2, 3]. Print a few test calls of the method.
def add_to_array(a, b)
... |
require "spec_helper"
describe FilterPhotos do
before :each do
@photos = create_list :photo, 20
@contestant = @photos.sample.owner
@params = {
contestant_id: @contestant.id,
tag: @photos.sample.tags.sample,
category: Photo::CATEGORIES.sample.to_s,
}
end
# TODO: add mongoid-... |
class AddColumnRequestStatusIdToWorkCertificate < ActiveRecord::Migration
def change
add_column :work_certificates, :request_status_id, :integer
end
end
|
class AddStepIdToMmsTools < ActiveRecord::Migration
def self.up
add_column :mms_tools, :step_id, :integer
end
def self.down
remove_column :mms_tools, :step_id
end
end
|
class ImgGrabController < ApplicationController
BASE_DIR = "./app/assets/images/"
def index
end
def booties
# Отображает все директории, в которых сохранены картинки.
begin
@dirs = []
Dir.foreach(BASE_DIR) do |dir|
if File.directory?("#{BASE_DIR}#{dir}")
# Получение до... |
########################################################
# Defines the main methods that are necessary to filter out low complexity reads
########################################################
class PluginLowComplexity < Plugin
#Returns an array with the errors due to parameters are missing
def check_params ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.