text stringlengths 10 2.61M |
|---|
require 'spec_helper'
RSpec.describe 'GET /posts/:id' do
let(:post) { create(:post) }
it 'check title h1' do
visit "/posts/#{post.id}"
expect(page.find('.post-header h1')).to have_content(post.title)
end
it 'check author full name' do
visit "/posts/#{post.id}"
expect(page).to have_content("#{... |
class ChangeTeamTableToEmployees < ActiveRecord::Migration
def change
rename_table :team, :employees
add_column :employees, :twitter, :string
change_column :employees, :github, :string
change_column :employees, :blog, :string
end
end
|
class ChangePhotoColumnFromFurnitures < ActiveRecord::Migration[6.0]
def change
change_column :furnitures, :photo, "varchar[] USING (string_to_array(photo, ','))"
end
end
|
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter { |c| Authorization.current_user = c.current_user }
protected
def permission_denied
flash[:error] = "Sorry, you are not allowed to access that page."
redirect_to root_url
end
end
|
require 'rubygems'
require 'nokogiri'
module FacebookApiCore
module Rest
class Response
class << self
def build http_response
Nokogiri::XML(http_response.body.strip).xpath("//fb:error_response", { "fb" => "http://api.facebook.com/1.0/"}).size == 0 ? Response.new(http_response) : Er... |
class TeamTaskWorker
include Sidekiq::Worker
sidekiq_options :queue => :tsqueue
def perform(action, id, author, fields = YAML::dump({}), keep_completed_tasks = false, options_diff = {})
RequestStore.store[:skip_notifications] = true
user_current = User.current
team_current = Team.current
fields ... |
require 'rubygems'
require 'spec'
class Life
attr_reader :live_cells
def initialize(live_cells)
@live_cells = live_cells
end
def to_a
@live_cells
end
def next_generation
next_gen = []
alive_neighbors.each do |cell,count|
next_gen << cell if alive_next(count, live_cells.inclu... |
class Bdba < ActiveRecord::Base
belongs_to :bdb, :foreign_key => 'bobjid'
end
# == Schema Information
#
# Table name: bdbas
#
# bobjid :integer(10)
# buser :string(16)
# btimestamp :datetime
# bmdtid :integer(10)
#
|
module QuickCharts
class Image
attr_accessor :type, :labels, :data
def initialize type, labels, data
@type = type
@labels = labels
@data = data
end
def fetch
QuickCharts::Api.call(@type, @labels, @data)
end
end
end |
class ReviewSerializer < ActiveModel::Serializer
attributes :id, :content, :user_id, :stars, :author_name
def author_name
author = User.find(@object.user_id)
author.username
end
# def movie_title
# movie = Movie.find(@object.movie_id)
# movie.title
# end
end
|
# @param {Integer} x
# @return {Integer}
def reverse(x)
stack = []
sign = ''
reverse_string = ''
str_x = x.to_s
str_x.each_char do |char|
if char == '-'
sign = char
else
stack << char
end
end
until stack.empty?
reverse_string += stack.pop
end
result = (sign + reverse_strin... |
require "rails_helper"
describe DeduplicationLog, type: :model do
context "associations" do
it { is_expected.to belong_to(:user).optional }
it { is_expected.to belong_to(:deduped_record) }
it { is_expected.to belong_to(:deleted_record) }
end
end
|
class Row < Struct.new \
:company,
:branch,
:region,
:service,
:price,
:duration,
:disabled
def initialize(raw_row)
super(*raw_row)
end
def price_cents
Float(price) * 100
end
def duration_minutes
Float duration
end
end
|
class CreateAgentSessions < ActiveRecord::Migration
def change
create_table :agent_sessions do |t|
t.integer :agent_id
t.datetime :start_time
t.datetime :end_time
t.string :hostname
t.string :ros_master_uri
t.string :session_status
t.string :token
t.timestamps null... |
# Read about factories at https://github.com/thoughtbot/factory_girl
FactoryGirl.define do
factory :admin do
sequence(:onid) {|n| "testonid#{n}" }
end
end
|
# Check Config
# Read and process CONFIG
class CheckConfig
def self.get(key)
# No setting: return nil
return nil if !CONFIG.has_key?(key)
value = CONFIG[key]
# Not language hash: return verbatim value
return value if !value.is_a?(Hash) || !value.has_key?('lang')
# No team context or no team l... |
describe IGMarkets::DealingPlatform::AccountMethods do
let(:session) { IGMarkets::Session.new }
let(:platform) do
IGMarkets::DealingPlatform.new.tap do |platform|
platform.instance_variable_set :@session, session
end
end
it 'can retrieve accounts' do
accounts = [build(:account)]
expect(s... |
# frozen_string_literal: true
module Grape
module Formatter
class Link
attr_reader :uri, :merge_params
def initialize(uri, merge_params)
@uri = uri
@merge_params = merge_params
end
def to_s
uri.dup.tap { |uri| uri.query = build_query(original_query.merge(merge_pa... |
#require 'bcrypt'
class User < ActiveRecord::Base
#email 转换成小写字母
before_save {self.email = email.downcase}
before_create :create_remember_token
validates :name,presence: true, length: {maximum: 50}
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email,presence: true,
format: {with: V... |
class RenameBeisIdToBeisIdentifier < ActiveRecord::Migration[6.1]
def change
rename_column :activities, :beis_id, :beis_identifier
end
end
|
require 'spec_helper'
include Warden::Test::Helpers
Warden.test_mode!
describe "Admin pages" do
subject { page }
before(:all){User.delete_all}
let(:admin) { FactoryGirl.create(:admin) }
before { login_as(admin, :scope => :admin, :run_callbacks => false) }
describe "index" do
before do
10.times... |
class GuidesController < ApplicationController
before_action :find_guide, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!, except: [:index, :show]
def index
@guides = Guide.all.order("created_at DESC")
end
def show
end
private
def find_guide
@guide = Guide.find(params[:id])
en... |
class RankingController < ApplicationController
layout 'review_site'
before_action :ranking
def ranking
product_ids = Review.group(:product_id).order('count_product_id DESC').limit(5).count(:product_id).keys
@ranking = product_ids.map { |id| Product.find(id) }
end
end
|
# -*- coding:utf-8 -*-
require_relative 'node'
require_relative 'primitive'
module MIKU
# MIKUがリストとして扱えるようにするためのmix-in。
# これをincludeするクラスは、car, cdr, setcar, setcdrを実装している必要がある。
module List
include Node
include Enumerable
# _beg_ 番目の要素を取得する。
# 範囲を超えていた場合nilを返す。
# Rangeが渡されたら、その範囲を切り取って返す。
... |
class Wallet < ActiveRecord::Base
belongs_to :user
validates_uniqueness_of :user_id
validates_presence_of :user_id, :balance
end
|
module BabySqueel
# This is the thing that gets added to Active Record's joins_values.
# By including Polyamorous::TreeNode, when this instance is found when
# traversing joins in ActiveRecord::Associations::JoinDependency::walk_tree,
# Join#add_to_tree will be called.
class Join
include Polyamorous::Tree... |
# COUNTING SHEEPS
# ------------------------------------------------------------------------------
# https://www.codewars.com/kata/54edbc7200b811e956000556/train/ruby
#
# Consider an array of sheep where some sheep may be missing from their place.We
# need a function that counts the number of sheep present in the a... |
module ApplicationHelper
def show_error_messages!(resource)
return '' if resource.errors.empty?
messages = resource.errors.full_messages.map { |msg| content_tag(:li, msg) }.join
sentence = I18n.t('errors.messages.not_saved',
count: resource.errors.count,
resource: resource.class.model_name.h... |
class RenameColumnInAdvertisements < ActiveRecord::Migration
def change
change_table :advertisements do |t|
t.rename :author, :title
end
end
end
|
class Ability
include CanCan::Ability
def initialize(user)
if user.has_role? :admin
can :manage, User
can :manage, Organization
end
can :manage, Catalog if user.organization
can :manage, Dataset do |dataset|
dataset.organization == user.organization
end
can :manage, Dist... |
def roll_call_dwarves(array)
array.each.with_index(1) do |value, index|
puts "#{index}: #{value}"
end
def summon_captain_planet(calls)
calls.map! { |calls| calls.capitalize + "!"}
end
def long_planeteer_calls(calls)
calls.any? { |calls| calls.length > 4 }
end
def find_the_cheese(array)
# the array below is... |
Vagrant.configure(2) do |config|
config.vm.box = "trusty-server-cloudimg-amd64-vagrant-disk1"
config.vm.box_url = "https://cloud-images.ubuntu.com/vagrant/trusty/current/trusty-server-cloudimg-amd64-vagrant-disk1.box"
config.vm.network "private_network", ip: "172.16.1.2"
config.vm.network "forwarded_port", gue... |
Rails.application.routes.draw do
root to: 'toppages#index'
get 'sessions/new'
get 'sessions/create'
get 'sessions/destroy'
get 'login', to: 'sessions#new'
post 'login', to: 'sessions#create'
delete 'logout', to: 'sessions#destroy'
get 'mycats', to: 'cats#index_my'
get 'yourcats', to: 'cats#index_y... |
class ChangePHoneIdType < ActiveRecord::Migration
def change
change_column :devices, :phoneid, :string
end
end
|
require 'spec_helper'
require 'yt/models/account'
describe Yt::Account, :device_app do
subject(:account) { Yt::Account.new attrs }
describe '#refresh' do
context 'given a valid refresh token' do
let(:attrs) { {refresh_token: ENV['YT_TEST_DEVICE_REFRESH_TOKEN']} }
# NOTE: When the token is refresh... |
namespace :check do
namespace :migrate do
task delete_relationships_created_by_bots: :environment do
n = Relationship.joins(:user).where(['users.type = ?', 'BotUser']).count
print "[#{Time.now}] Deleting #{n} relationships created by authenticated bots... "
Relationship.joins(:user).delete_all([... |
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe TrophyUser, type: :model do
it 'is valid with user and trophy' do
trophy_user = create(:trophy_user)
expect(trophy_user).to be_valid
end
context 'when associating' do
it { is_expected.to belong_to(:trophy) }
it { is_expected.to... |
#Gemfile: gem 'bcrypt'
#Config/environment.rb: require 'bcrypt'
# DEFINE METHODS IN class User
class User < ActiveRecord::Base
include BCrypt
def password
@password ||= Password.new(password)#accepts a password string as an argument
# Creates a hashed password. Looks like this ""$2a$10$Iiiuf7562HGz3iBw/... |
# Public: Takes two integers and returns the largest one
#
# num1 - One of the intergers used for comparison between one other integer
# num2 - One of the intergers used for comparison between one other integer
#
# Examples
#
# max_of_two(1, 2)
# # => 2
# Returns the largest integer
def max_of_two(num1, num2)... |
require 'rubygems'
require 'sinatra'
require 'haml'
require 'sass'
require 'json'
enable :lock
use Rack::Auth::Basic do |username, password|
username == 'guest' && password == 'please'
end
configure do
$tz = File.open '/dev/cu.usbmodem12341', 'r+'
end
before do
content_type "application/json"
end
helpers do
... |
class AddProfileFieldsToOAuthAccounts < ActiveRecord::Migration[5.1]
def change
add_column :oauth_accounts, :star_url, :text
add_column :oauth_accounts, :rank, :integer
add_column :oauth_accounts, :level, :integer
add_column :oauth_accounts, :level_url, :text
end
end
|
class Message < ApplicationRecord
# associations
belongs_to :chatroom
belongs_to :user
end
|
class Admin::StockproductsController < ApplicationController
require 'csv'
# Define the layout to be used
layout "store_merchant_layout"
# Define the before_action elements
before_action :set_stockproduct, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!
before_action :verify_pe... |
class Task < ApplicationRecord
# Associations
belongs_to :user
has_many_attached :attachments
# Validations
validates :description, presence: true
validates :due, presence: true
# Callbacks
before_save :check_max_position, if: :position
# Other
acts_as_list scope: :user, add_new_at: :top, top_of_... |
class Human
attr_reader :player_number, :lives
def initialize(num)
@player_number = num
@lives = 5
end
def front_back
position = get_position
until valid_position?(position)
puts "Please pick (f) or (b)."
position = get_position
end
position
end
def player_turn
le... |
require './src/interpreter/scope'
require './src/interpreter/errors'
RSpec.describe Interpreter::Scope, 'variables and function scopes' do
before :example do
@current_scope = Interpreter::Scope.new
end
describe '#set_variable, #get_variable' do
it 'can store and retrieve variables' do
@current_sco... |
# resources/file.rb
property :path, Path, identity: true
property :mode, Integer
property :content, String
recipe do
converge do
IO.write(path, content) if content
::File.chmod(mode, path) if mode
end
end
def load
if ::File.exist?(path)
mode ::File.stat(path).mode
content IO.read(path)
else
... |
class CobrandParamsCobrandIdAndKey < ActiveRecord::Migration
def self.up
add_index :cobrand_params, [:cobrand_id, :key], :name => :cobrand_params_cobrand_id_and_key_index
end
def self.down
remove_index :cobrand_params, :name => :cobrand_params_cobrand_id_and_key_index
end
end
|
require 'rails_helper'
describe Meta::FormatsController do
before(:all) do
@game = create(:game)
@admin = create(:user)
@admin.grant(:edit, :games)
@user = create(:user)
end
describe 'GET #index' do
it 'succeeds for authorized user' do
sign_in @admin
get :index
expect(r... |
# Usa-se o menor "<" para indicar a herança
# No ruby não existe herança múltipla
class Pessoa
attr_accessor :nome, :email
end
class PessoaFisica < Pessoa
attr_accessor :cpf
def falar(texto)
texto
end
end
class PessoaJuridica < Pessoa
attr_accessor :cnpj
def pagar_fornecedor
... |
# 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 File.expand_path(File.dirname(__FILE__) + "/base_page")
class HomePage < BasePage
def initialize
super
selenium.window_maximize
@link_write_a_review = "id=writeReviews"
@link_join_the_community = "link=Join the Community"
#TODO to be moved to Myhome or reviews page
@myho... |
#!/usr/bin/env ruby
require_relative "LinkedList.rb"
class MyHash
attr_reader :hashA
def initialize(p, w, a)
@p = p
@w = w
@a = a
@m = 2**p
@s = @a * 2**@w
@hashA = Array.new(@m) {LinkedList.new(nil)}
end
def hashFunc(key)
h = ((2**@p*((key*@s) % 2**@w))/2**@w).floor
return h
end
def insert(ke... |
require("minitest/autorun")
require('minitest/reporters')
Minitest::Reporters.use! Minitest::Reporters::SpecReporter.new
require_relative("../drink")
class DrinkTest < MiniTest::Test
def setup
@drink = Drink.new("wine", 4.00, 5)
end
def test_drink_has_name
assert_equal("wine", @drink.name())
end
... |
class ForumsController < ApplicationController
before_action :set_forum, only: [:show, :edit, :update, :destroy]
before_action :set_users
before_action :set_new_forum, except: [:show, :edit, :update, :destroy]
before_filter :authenticate_user!
# GET /forums
# GET /forums.json
def index
@forums = Foru... |
require './lib/x_move_sequence'
require './lib/o_move_sequence'
class ComputerPlayer
include XMoveSequence
include OMoveSequence
attr_accessor :turn_number, :optimal_move_sequence
attr_reader :mark
def initialize(first_player)
@mark = get_mark(first_player)
@turn_number = 1
@optimal_move_sequenc... |
module SimpleEnum
extend ActiveSupport::Concern
included do
def initialize(name, id)
@name = name
@id = id
end
attr_reader :name, :id
extend Enumerable
def self.all_collection
@all ||= []
end
end
module ClassMethods
def enum(*args)
instance = new(*arg... |
class Bip < Formula
homepage "https://bip.milkypond.org" # Self-signed cert.
url "https://mirrors.kernel.org/debian/pool/main/b/bip/bip_0.8.9.orig.tar.gz"
sha256 "3c950f71ef91c8b686e6835f9b722aa7ccb88d3da4ec1af19617354fd3132461"
revision 1
bottle do
cellar :any
sha256 "73a885e1f2655a3c6d8ff108559e001... |
#Note that things behave a bit differently depending on whether the storage is versioned.
# If not, then in the initial delete stage we do _not_ really delete the content. We just leave it in place.
# Then in the final delete stage we go ahead and delete it. If restore is requested nothing needs to happen
# to the cont... |
require "fog/compute/models/server"
module Fog
module Compute
class Google
class Server < Fog::Compute::Server
identity :name
# @return [Boolean]
attribute :can_ip_forward, :aliases => "canIpForward"
# @return [String]
attribute :cpu_platform, :aliases => "cpuPlatf... |
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# name :string
# email_id :text
# phone_no :string
# password_digest :string
# created_at :datetime
# updated_at :datetime
# admin :boolean default(FALS... |
require 'pry'
class Song
attr_accessor :name, :artist
@@all = []
def initialize(name)
@name = name
@@all << self
end
def self.all
@@all
end
def artist_name
artist.name if artist
end
def self.song_count
Song.all.count
end
end
#eatit = Song.new("Eat It")
#puts "something"
|
module GroupDocs
class Document::Rectangle < Api::Entity
# @attr [Float] x
attr_accessor :x
# @attr [Float] y
attr_accessor :y
# @attr [Float] width
attr_accessor :width
# @attr [Float] height
attr_accessor :height
# Human-readable accessors
alias_accessor :w, :width
alia... |
module ThreeScale
module Backend
module Validators
class Limits < Base
def apply
limits_app_ok = status.application ? valid_limits_app? : true
limits_ok = if limits_app_ok
status.user ? valid_limits_user? : true
else
... |
require 'account'
describe Account do
let(:credit) { double :transaction, amount: 1000, date: '10-01-2012' }
let(:credit2) { double :transaction, amount: 2000, date: '13-01-2012' }
let(:debit) { double :transaction, amount: -500, date: '14-01-2012' }
describe 'initialize' do
it 'is initialized with a ba... |
require 'rubygems'
require 'test/unit'
require 'active_support/core_ext'
$LOAD_PATH.unshift(File.dirname(__FILE__))
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
##
# Simulate enough of ActiveRecord::Base that objects can be used for testing.
#
module ActiveRecord
class Base
def initia... |
class ClientsController < ApplicationController
def index
@client = Client.all
end
def show
@client = Client.find(params[:id])
@contracts = Contract.where("client_id = ?", params[:id])
end
def new
@client = Client.new
end
def create
@client = Client.new(client_params)
if @client... |
class AddDealsGenre < ActiveRecord::Migration
def change
add_column:deals,:genre,:string
end
end
|
ActiveAdmin.register Timeline do
menu priority: 2, label: "Životopis", parent: "O mne"
controller do
def create
super do |format|
redirect_to collection_url and return if resource.valid?
end
end
def update
super do |format|
redirect_to collection_url and return if re... |
class Userupgrade < ApplicationRecord
#Regex information for userupgrade
VALID_VALUE_REGEX = /\A[0-9]+\z/i
#Validates the userupgrade information upon submission
validates :pouchbase, presence: true, format: { with: VALID_VALUE_REGEX}
validates :pouchinc, presence: true, format: { with: VALID_VALUE_REGE... |
class PicturesController < ApplicationController
before_action :login_required
before_action :set_current_user_pictures, only: [:show, :edit, :update, :destroy]
def all_picture
redirect_to :new_picture
end
def index
@pictures = current_user.pictures.order(:id)
end
def show
end
def n... |
class BidsController < ApplicationController
before_action :authenticate_user!
def create
@auction = Auction.find(params[:auction_id])
@bid = @auction.bids.new(bids_params)
@bid.user = current_user
alert1 = "alert('You cant bid on you own auction, fool');"
alert2 = "alert('Please enter a valid... |
# frozen_string_literal: true
# Authentication common functions
module Authentication
def verify_auth_token(access_token: nil, provider: 'google', identifier: nil)
account = Account.find_by_credentials(provider, identifier, access_token)
return account.user if account.present?
userinfo = obtain_userinfo... |
# frozen_string_literal: true
require 'rails_helper'
describe Api::V1::LinesController do
let!(:line1) { create(:line, source_id: 2, name: 'S42') }
let!(:line2) { create(:line, source_id: 3, name: 'S41') }
let!(:delay) { create(:delay, line: line2, delay_in_minutes: 4) }
describe '#show' do
context 'whe... |
require './test/test_helper'
gem 'minitest', '~> 5.2'
require 'minitest/autorun'
require 'minitest/pride'
require './lib/classes/game_teams'
require 'csv'
require 'pry'
class GameTeamTest < Minitest::Test
def setup
game_path = './data/game.csv'
team_path = './data/team_info.csv'
game_teams_path = './dat... |
require 'spec_helper'
require 'aws-sdk'
RSpec.describe SnapDeploy::Provider::AWS::S3 do
subject(:cmd) { SnapDeploy::Provider::AWS::S3.new(nil, {}, {}) }
before do
AWS.stub!
allow(ENV).to receive(:[]).with(anything).and_call_original
allow(ENV).to receive(:[]).with('AWS_ACCESS_KEY_ID').and_return(Secu... |
class Department < ActiveRecord::Base
belongs_to :employee, :foreign_key => 'manager_id'
def to_s
self.name
end
end
|
require_relative 'spec_helper'
module PacketGen
module Plugin
describe NonESPMarker do
describe 'bindings' do
it 'in UDP packets with port 4500' do
expect(PacketGen::Header::UDP).to know_header(NonESPMarker).with(dport: 4500)
expect(PacketGen::Header::UDP).to know_header(NonESP... |
class Template
class EditPresenter
def record
@record ||= Setting.find_by!(key: 'template')
end
def template
@template ||= begin
template_data = begin
JSON.parse(record.value)
rescue
{}
end
Template.new(template_data)
end
end
... |
# encoding: utf-8
require "spec_helper"
require "logstash/patterns/core"
describe "FIREWALLS" do
let(:pattern104001) { "CISCOFW104001" }
context "parsing a 104001 message" do
let(:value) { "(Secondary) Switching to ACTIVE - Service card in other unit has failed" }
subject { grok_match(pattern10... |
require 'spec_helper'
describe Protocolize::ActsAsProtocolable do
let(:my_model) { MyModel.new(name: "My model") }
describe '.acts_as_protocolable' do
it 'should call generate_protocol after create a model' do
expect(my_model).to receive(:generate_protocol)
my_model.run_callbacks(:create)
en... |
#!/usr/bin/env ruby -wKU
# encoding: utf-8
###################################################################
# Make a Makefile for Make from a YAML project file
###################################################################
# First include the functions in the jamoma lib
libdir = "."
Dir.chdir libdir ... |
class ConcessionTypeController < ApplicationController
respond_to :json
before_filter :authorize
before_action :find_company , :only =>[:index , :new , :create ]
def index
concessions = @company.concessions.select("id , name")
render :json=>concessions
end
def new
end
def creat... |
class Month < ActiveRecord::Base
has_many :articles
has_many :month_counts
has_many :wordbanks, through: :month_count
validates :month, uniqueness: true
by_star_field :month
end
|
require 'rails_helper'
RSpec.describe EventsController, type: :controller do
describe "Get #index" do
it "responds successfully with an HTTP 200 status code" do
get :index
expect(response).to be_success
expect(response).to have_http_status(200)
end
it "renders the index template" do
... |
class CreateRaceParticipants < ActiveRecord::Migration[5.1]
def change
create_table :race_participants do |t|
t.datetime :start_time
t.datetime :end_time
t.text :typed_text
t.integer :total_key_stroke
t.integer :wpm
t.integer :accuracy
t.timestamps
end
end
end
|
# encoding: utf-8
module Brewed
##
## == BrewedLog ==
##
class BrewedLog
attr_reader :log_index, :out_logs, :debug_logs, :failures
def initialize()
@failures = []
@log_index = {}
@out_logs = []
@debug_logs = []
end
##
# Begin logging to a new active log dest... |
require "rails_helper"
RSpec.describe Api::V1::TransactionsController, type: :controller do
before do
3.times {FactoryGirl.create(:transaction)}
end
context "#index" do
it "returns the right number of transactions" do
transaction_count = Transaction.count
get :index, format: :json
ex... |
class Rum < ApplicationRecord
belongs_to :user
has_many :orders
has_many :reviews
mount_uploader :photo, PhotoUploader
validates :name, presence: true
validates :price, presence: true
validates :volume, presence: true
validates :origin, presence: true
geocoded_by :origin
after_validation :geocode, ... |
class EntriesController < ApplicationController
def new
@entry = Entry.new
end
def create
@entry = Entry.new(entry_params)
@entry.save
redirect_to @entry
end
def show
@Entry = Entry.find(params[:id])
end
def index
@entry = Entry.all
end
def entry_params
params.require(:entry... |
module SoupsHelper
def finished_soups?(state)
state == "finished"
end
def render_soup_state(soup)
soup.finished? ? "finished" : soup.pending? ? "pending" : ""
end
def format_description(soup)
simple_format(strip_tags(soup.description))
end
end
|
class Course < ActiveRecord::Base
attr_accessible :code, :description, :name, :semester, :year
belongs_to :professor # foreign key - professor_id
belongs_to :department # foreign key - department_id
has_many :evaluations
has_and_belongs_to_many :students # foreign keys in an invisible join table
... |
require "aws-sdk"
require './lib/shared/settings'
require './lib/shared/sns'
require './lib/shared/transcoder'
require './lib/shared/s3_service'
require './lib/shared/log_helper'
class Setup
include LogHelper
def initialize
Aws.config.update(
region: Settings.aws_region,
credentials: Aws::Creden... |
FactoryGirl.define do
factory :news do
name
body
published_at { generate :date }
end
end
|
# frozen_string_literal: true
# The SideTradeRegulatoryParser is responsible for the <TrdRegTS> mapping. This tag is one of many tags inside
# a FIXML message. To see a complete FIXML message there are many examples inside of spec/datafiles.
#
# Relevant FIXML Slice:
#
# <TrdRegTS Typ="1" TS="2015-02-19T10:53:37-06:00... |
Given("I am on the puppy adoption site") do
visit(HomePage)
end
When("I click the View Details button") do
navigate_to(DetailsPage)
end
When("I click the View Details button for {string}") do |name|
on(HomePage).select_puppy name
end
When("I click the Adopt Me button") do
on(DetailsPage).add_to_cart
end
Whe... |
require 'spec_helper'
describe Ng::MinLengthValidator do
let(:message) { "test message" }
let(:title) { "I am a title" }
let(:order) { 1 }
let(:minimum) { 100 }
let(:arg) { ActiveModel::Validations::LengthValidator.new message: message, title: title, order: order, minimum: minimum, attributes: ['foo'] }
le... |
class FixColumnType < ActiveRecord::Migration
def change
rename_column :holidays, :type, :sort
end
end
|
require File.join(File.dirname(__FILE__), '..', "spec_helper")
require "rspec/matchers/dm/belongs_to"
describe DataMapperMatchers::BelongsTo do
it "should pass for for working association" do
Comment.should belongs_to(:post)
end
it "should fail for improper associations" do
lambda { Comment.should_n... |
class EmailTemplate < ActiveRecord::Base
attr_accessor :state_list #dont store this field in the database - only in the object
attr_accessible :body, :subject, :state_list
has_and_belongs_to_many :states
after_save :update_states
private
def update_states
states.delete_all
selected_states = state_li... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.