text stringlengths 10 2.61M |
|---|
class School
attr_accessor :roster, :name
# @roster = {}
def initialize(name)
@roster = {}
@name = name
end
def add_student(name, grade)
@roster[grade] ||= []
@roster[grade] << name
end
def grade(grade)
new_roster = @roster.select do |g, students|
g == grade
end
new_roste... |
# Using the code from the previous exercise, add a setter method named #name=. Then, rename kitty to 'Luna' and invoke #greet again.
class Cat
attr_accessor :name
def initialize(n)
@name = n
end
def greeting
puts "Hello, my name is #{name}."
end
end
kitty = Cat.new('Sophie')
kitty.greeting
kitty.n... |
require_relative('../db/sql_runner')
class Student
attr_accessor :first_name, :last_name, :age, :id, :house_id
def initialize( options )
@id = options['id'].to_i
@first_name = options['first_name']
@last_name = options['last_name']
@age = options['age'].to_i
@house_id = options['house_id'].to... |
# Copyright 2019 The inspec-gcp-cis-benchmark Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... |
class AddUriToShortenedUrls < ActiveRecord::Migration
def change
# add new stuff
add_column :shortened_urls, :uri_hash, 'char(8)', :default => '', :null => false, :after => :url_hash
add_column :shortened_urls, :uri, :string, :default => '', :null => false, :after => :url
add_index :shortened_urls, :u... |
require 'rails_helper'
RSpec.describe "product_costs/new", type: :view do
before(:each) do
assign(:product_cost, ProductCost.new(
:product_id => 1,
:category => "MyString",
:name => "MyString",
:cost_cents => 1,
:cost_currency => "MyString",
:cost_percentage => "9.99"
))
... |
ARGV << '-o' << '127.0.0.1' # work around localhost issue
require 'sinatra'
require 'sinatra/reloader'
SECRET_NUM = rand(100)
def check_guess(guess_num)
difference = (SECRET_NUM - guess_num).abs
if guess_num > SECRET_NUM
if difference > 5
message = "Way too high!"
else
message = "Too high"
... |
class User < ActiveRecord::Base
attr_accessible :email, :name
validates :email, :presence => true, :uniqueness => true
validates :name, :presence => true
has_many(:polls,
:class_name => "Poll",
:foreign_key => :author_id,
:primary_key => :id,
:dependent => :destr... |
class Location < ActiveRecord::Base
has_many :birthday_deals
has_many :company_locations
has_many :users
has_many :birthday_parties
geocoded_by :location_name, :latitude => :lat, :longitude => :lng
after_validation :geocode, if: ->(location){location.city_changed? || location.state_changed? }
def locati... |
# Settings specified here will take precedence over those in config/environment.rb
# You have to enable the two caching settings here to get acts_as_audited
# to record entries in development
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is... |
require 'facilities_management/fm_buildings_data'
module FacilitiesManagement
module Beta
class ProcurementsController < FrameworkController
before_action :set_procurement, only: %i[show edit update destroy results]
before_action :set_deleted_action_occurred, only: %i[index]
before_action :set_e... |
class DmConfig < ActiveRecord::Base
set_table_name "dbconfigs"
named_scope :enabled, :conditions => {:disabled => false}
def database
Dm::DBPool[self.name]
end
def self.setup_db_pool
Dm::DBPool.setup(self.enabled.all.build_hash{|e|[e.name, e.connect_url]})
end
def connect_url
... |
class AssignmentMailer < ApplicationMailer
def new_assignment_email(user , assignment)
@assignment = assignment
@user = user
mail(to: @user.email, subject: "New Assignment in " + Group.find_by(id:(@assignment.group_id)).name )
end
def update_assignment_email(user, assignment)
@assignment = assi... |
class BadgeRuleService
def initialize(user_passed_test)
@user_attempt = user_passed_test
@user = user_passed_test.user
@badges = Badge.includes(:badge_rule)
end
def check_awards
return [] unless @user_attempt.success?
@badges.select { |b| send("rule_#{b.badge_rule.rule}", b.badge_rule.argumen... |
require 'rails_helper'
describe ProductsController, type: :controller do
before do
@product = FactoryBot.create(:product)
@user = FactoryBot.create(:user)
# @admin = FactoryBot.create(:admin)
end
describe 'GET #index' do
it 'renders products index page' do
get :index
expect(respo... |
class Lolita::RestController < ApplicationController
include Lolita::ControllerAdditions
include Lolita::Hooks
add_hook :before_new, :after_new, :before_create,:after_create,:before_edit,:after_edit
add_hook :before_update,:after_update,:before_destroy,:after_destroy,:before_index,:after_index
add_hook :befo... |
module HasUserData
def users_full_name
"#{object.user.name} #{object.user.surname}"
end
end
|
require "rails_helper"
RSpec.feature "VisitorCanViewJobs", type: :feature do
context "as a visitor" do
let!(:company) { Company.create(name: "ABC Company", information: "xyz") }
let!(:job) do
company.jobs.create(title: "Jr Dev",
description: "As a Junior developer, you will co... |
class RoleCheck
prepend SimpleCommand
def initialize(current_user, feature)
# READ = Permission 1
# UPDATE = Permission 2
# CREATE = Permission 4
# DELETE = Permission 8
# Note: feature is code number from Constants::APP_MOD_XXXXXXXXX
# Exception if missing required params
raise Argum... |
class QuestionHelpMessage < ActiveRecord::Base
include Localizable
include Authority::Abilities
self.authorizer_name = "AdminAuthorizer"
has_many :questions
localize :message
end
|
module EventsCommand
def events!(*args)
if registered?
events = if 'all'.in? args
User.includes(:events).find_by(chat_id: chat['id']).events
else
User.includes(:events).where(chat_id: chat['id']).with_active_events.first&.events || []
end
... |
class Group < ActiveRecord::Base
has_many :groupings
has_many :users, through: :groupings
end
|
# encoding: UTF-8
# Copyright 2012 Twitter, Inc
# http://www.apache.org/licenses/LICENSE-2.0
module TwitterCldr
module Localized
class LocalizedNumber < LocalizedObject
attr_reader :type, :format
def initialize(obj, locale, options = {})
@type = options[:type]
@format = options[:fo... |
# 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 Restaurant
@@all = []
def self.all
@@all
end
attr_accessor :name
def initialize(name)
@name = name
self.class.all << self
end
def self.find_by_name(name)
self.all.find {|restaurant| restaurant.name == name}
end
def reviews
Review.all.select {|review| review.restaurant =... |
# Processes deposit transactions on Cryptsy and credits accounts at the current spot price
class ReceiveWorker
include Sidekiq::Worker
def perform
client = CryptoTeller.cryptsy_client
transactions = Sidekiq.redis do |redis|
client.transactions.select do |tx|
tx.type == 'Deposit' && redis.sad... |
=begin
Implement a method #substrings that takes a word as the first argument and then an array of valid
substrings (your dictionary) as the second argument. It should return a hash listing each
substring (case insensitive) that was found in the original string and how many times it was found.
=end
def substr... |
#!/usr/bin/env ruby
require_relative '../../../framework/Feature'
class InformGeneralInstructions
@@name = :inform_general_instructions
@@feature = Feature.new(@@name)
@@feature.add_alteration(
:instance_method,
:ERS,
:inform,
lambda do
"#{inform_general_instr... |
# == Schema Information
#
# Table name: questions
#
# id :integer not null, primary key
# text :string not null
# poll_id :integer not null
# created_at :datetime
# updated_at :datetime
#
class Question < ActiveRecord::Base
validates :text, :poll_id, presence: true
... |
# Copyright 2014 Square Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... |
#!/usr/bin/env ruby
# frozen_string_literal: true
$LOAD_PATH.unshift("#{__dir__}/../lib")
require 'optparse'
require 'growi-client'
require 'growi/image_converter'
def run
options = {}
options[:dry_run] = true
OptionParser.new do |opt|
opt.banner = 'Usage: growi-image_converter [options]'
opt.version ... |
class FixColumnName < ActiveRecord::Migration
def change
rename_column :councils, :CouncilEmail, :email
end
end
|
require "test_helper"
describe UsersController do
describe "auth_callback" do
it "can log in an existing user" do
user = login(users(:ada))
must_respond_with :redirect
end
it "logs in an existing user" do
start_count = User.count
user = users(:ada)
login(user)
... |
# Configure your SMS API settings
require 'net/http'
require 'yaml'
require 'translator'
require 'assigned_package'
require 'sms_package'
class SmsManager
attr_accessor :recipients, :message
BATCHING_LMIT = 250
def self.split_ids_to_batches(ids)
ids = fetch_ids_list(ids) if (ids.present? and (ids... |
# encoding: UTF-8
$: << '../lib'
require 'minitest/autorun'
require 'ruby-hl7'
class ObxSegment < MiniTest::Test
def setup
@base = "OBX||TX|FIND^FINDINGS^L|1|This is a test on 05/02/94."
end
def test_initial_read
obx = Ruby::HL7::OBX.new @base
assert_equal( "", obx.set_id )
assert_equal( "TX", ... |
namespace :db do
require 'sequel'
Sequel.extension :migration
DB = Sequel.connect('postgres://postgres@localhost/playground')
desc 'Prints current schema version'
task :version do
version = get_file_version()
puts "Schema version: #{version}"
end
desc 'Perform migration up to latest migration av... |
class Author < ApplicationRecord
def discount() 10 end
has_many :books
has_many :published, as: :publisher, foreign_key: :publisher_id, class_name: 'Book'
end
|
Rails.application.routes.draw do
root to: 'pages#home'
get '/portfolio', to: 'pages#portfolio'
get '/resume', to: 'pages#download_pdf'
get '/contact', to: 'pages#contact'
end
|
# frozen_string_literal: true
require 'ostruct'
require './commands/ingredients/create'
RSpec.describe Commands::Ingredients::Create do
describe "#result" do
let(:params) { Sinatra::IndifferentHash.new }
let(:request) { instance_double(Sinatra::Request) }
let(:command) { described_class.new(request, par... |
module CDI
module V1
module Discussions
class UpdateService < BaseUpdateService
include V1::ServiceConcerns::DiscussionParams
include V1::ServiceConcerns::SurveyAttachmentParams
record_type ::Discussion
def record_params
discussion_params
end
def... |
require 'faker'
namespace :db do
desc "Fill db with sample data"
task :populate => :environment do
Rake::Task['db:reset'].invoke
# Create one known user
#admin = User.create(:first_name => "john", :last_name => "malkovich", :email => "john@malkovich.com",
# :password => "pa... |
require 'rails_helper'
RSpec.describe Member, type: :model do
describe 'validations' do
it 'has a valid factory' do
expect(FactoryGirl.create(:member)).to be_valid
end
end
describe 'associations' do
it { should have_many(:albums) }
it { should have_many(:groups) }
it { should have_many... |
require "application_system_test_case"
class MissionsTest < ApplicationSystemTestCase
setup do
@mission = missions(:one)
end
test "visiting the index" do
visit missions_url
assert_selector "h1", text: "Missions"
end
test "creating a Mission" do
visit missions_url
click_on "New Mission"
... |
require 'spec_helper'
require File.join(File.dirname(__FILE__), '../app/', 'cf-proxy-broker.rb')
require 'bunny'
describe CFProxyBroker do
def app
@app ||= CFProxyBroker
end
before(:all) do
ActiveRecord::Base.logger = nil
# Automigrate if needs migration
if ActiveRecord::Migrator.needs_migrati... |
module Api
module Models
module Validatable
extend ActiveSupport::Concern
VALIDATIONS = [:validates_presence_of, :validates_uniqueness_of, :validates_format_of,
:validates_confirmation_of, :validates_length_of].freeze
def self.required_fields(klass)
[]
end
... |
class Product < ActiveRecord::Base
belongs_to :search
# Creation a new product using data from API
def self.create_from_api(api_item)
create(
name: api_item['title'].try(:first),
link: api_item['viewItemURL'].try(:first),
price: api_item['sellingStatus'][0]['convertedCurrentPrice'][0]['__va... |
##
# SyncRemoteArticles
#
# Sync with the Remote Article API's
# This isn't on the "rake_tasks" queue because it
# can be triggered from the CMS.
module Job
class SyncRemoteArticles < Base
@queue = "#{namespace}:remote_articles"
class << self
def perform
@synced = RemoteArticle.sync
sel... |
require 'protip/decorator'
module Protip
module Resource
# Internal helpers for non-resourceful member/collection methods. Never use these directly;
# instead, use the instance/class methods which have been dynamically defined on the resource
# you're working with.
module ExtraMethods
def self.... |
# encoding: utf-8
#
# © Copyright 2013 Hewlett-Packard Development Company, L.P.
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
#... |
class Winevariety < ActiveRecord::Base
has_and_belongs_to_many :wines
end
|
# frozen_string_literal: true
require "spec_helper"
RSpec.describe(Jekyll::GitHubMetadata::Pages) do
context "enterprise" do
before(:each) { ENV["PAGES_ENV"] = "enterprise" }
after(:each) { ENV["PAGES_ENV"] = "test" }
let(:ghe_domain) { "ghe.io" }
it "disables custom domains" do
expect(desc... |
class AddRequiresUserAgreementToDocumentTemplates < ActiveRecord::Migration[5.0]
def change
rename_column :document_templates, :requires_agreement, :requires_employee_agreement
add_column :document_templates, :requires_employer_agreement, :boolean, null: false, default: false
DocumentTemplate.unscoped.up... |
require_relative "Board"
class Game
attr_reader :counts
def initialize
@board = Board.new
@board.render
@counts = 0
end
def turn_card
puts "Please enter the position of the card you'd like to flip, (e.g. '2,3'):"
guess_1 = gets.chomp.split(",").map { |ele| ele... |
# frozen_string_literal: true
require "spec_helper"
describe GraphQL::Introspection::DirectiveType do
let(:query_string) {%|
query getDirectives {
__schema {
directives {
name,
args { name, type { kind, name, ofType { name } } },
locations
isRepeatable
... |
FactoryBot.define do
factory :provider_ibm_terraform, :class => "ManageIQ::Providers::IbmTerraform::Provider", :parent => :provider do
sequence(:url) { |n| "example_#{seq_padded_for_sorting(n)}.com" }
end
end
|
require 'rails_helper'
RSpec.feature "Admin can delete categories" do
scenario "they do not see the deleted category" do
create_and_stub_admin
categories = %w(funny silly crazy).map do |category_name|
Category.create(name: category_name)
end
visit admin_categories_path
click_on "funny"
... |
class ChangedLocationsAddedUgroupsCountAndDeletedGroupsCount < ActiveRecord::Migration
def self.up
add_column :locations, :ugroups_count, :integer
remove_column :locations, :groups_count
end
def self.down
add_column :locations, :groups_count, :integer, :limit=>nil, :default=>nil
remove_column :... |
require 'spec_helper'
describe AccessSchema do
describe ".build" do
it "returns schema"
end
describe ".build_file" do
it "returns schema"
end
describe ".configure" do
it "passess given block to ConfigBuilder.build method" do
block = proc {}
AccessSchema::ConfigBuilder.should_receiv... |
require 'spec_helper'
describe TheGrid::Config do
context "when initializes" do
its(:commands_lookup_scopes) { should eql [] }
its(:prettify_json) { should be_false }
end
context "when applying specified values" do
let(:command) { TheGrid::Api::Command }
let(:builder) { TheGrid::Builder::Json }
... |
class Api::V1::SessionsController < Devise::SessionsController
before_action :sign_in_params, only: :create
before_action :load_user, only: :create
before_action :valid_token, only: :destroy
skip_before_action :verify_signed_out_user, only: :destroy
def create
if @user.valid_password?(sign_in_params[:pas... |
class DepartmentsController < ApplicationController
include Searchable
include ContactableConcern
expose :departments, -> { search(@active_company.departments.includes_associated, sortable_fields) }
expose :department, id: ->{ params[:slug] }, scope: ->{ @active_company.departments.includes_associated }, find_... |
ENV['RACK_ENV'] = 'test'
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
RSpec.configure do |config|
config.when_first_matching_example_defined(:db) do
require_relative 'support/db'
end
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_de... |
feature "bid_newspapers - List" do
context 'Visitor' do
scenario "Access invalid" do
visit bid_newspapers_path
expect(current_path).to eq new_session_path
end
end
context 'Admin' do
let(:user) { create :user }
background do
login user.email, user.password
end
scenario... |
%w[neutron-server python-neutronclient].each do |pkg|
package pkg do
action :install
end
end
service 'neutron-server' do
action :nothing
end
template 'Neutron controller api-paste config' do
path '/etc/neutron/api-paste.ini'
owner 'root'
group 'neutron'
mode '0644'
source 'neutron/api-paste.ini.er... |
module QuickbloxApi
# source: https://github.com/revans/quickblox/
# TODO: logic should be simplified and moved into helpers
class Encoder
def self.encode!(sorted_params)
new(sorted_params).encode!
end
def initialize(sorted_params)
@sorted_params = sorted_params
end
def encode!
... |
class DerivedAssessmentGroupSetting < ActiveRecord::Base
belongs_to :derived_assessment_group
serialize :value, DerivedAssessmentGroup::Setting if AssessmentGroup.table_exists?
def formula
self.value.formula
end
def weightage
self.value.weightage || {}
end
def report_settings
self.va... |
# frozen_string_literal: true
module Knuckles
# The Keygen module provides simple cache key generation. The global keygen
# strategy can be changed at the top level by configuring `Knuckles.keygen`.
#
# Any object that responds to `expand_key` with a single argument can be
# used instead.
#
# @example Ch... |
class Item < Struct.new(:name, :path, :exception)
def selected?(params)
name.pluralize.downcase == params[:controller] and
not exception?(params)
end
private
def exception?(params)
exception.call(params) unless exception.nil?
end
end
module NavigationHelper
def items
@items ||=
[
... |
class BookComment < ApplicationRecord
belongs_to :user
belongs_to :book, counter_cache: :book_comments_count
validates :comment, presence: true
end
|
module Axon
# == A Nearest-neighbor Image Scaler
#
# Axon::NearestNeighborScaler scales images quickly using the nearest-neighbor
# interpolation method.
#
# Nearest-neighbor interpolation selects the value of the nearest pixel when
# calculating colors in the scaled image.
#
# == Example
#
# n ... |
require File.dirname(__FILE__) + '/../test_helper'
class DraftTest < ActiveSupport::TestCase
fixtures :drafts
def test_should_be_valid
assert Draft.new.valid?
end
def test_nil_content
assert_equal Hash.new, Draft.new.content
end
def test_find_for_issue
assert Draft.find_for_issue(:element_id... |
require "rails_helper"
describe Area do
it { should have_many(:positions) }
it { should allow_value('foo').for(:name) }
it { should_not allow_value('').for(:name) }
end
|
module Brainstem
module QueryStrategies
class NotImplemented < StandardError
end
class BaseStrategy
def initialize(options)
@options = options
@last_count = nil
end
def execute(scope)
raise NotImplemented, 'Your strategy class must implement an `execute` method'... |
name 'gnops_bind9'
maintainer 'Thomas Insel'
maintainer_email 'tinsel@gracenote.com'
license 'Apache 2.0'
description 'Installs/Configures BIND 9'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version '1.4.8'
|
# encoding: utf-8
require 'spec_helper'
require 'models/projects'
require 'action_control'
require 'vboard_call_controller'
describe Init do
let(:mock_call) { double 'Call', :to => '1112223333', :from => "2223334444" }
let(:metadata) { {} }
subject { Init.new(mock_call, metadata) }
it "should have empty met... |
class AddPointsToSpreePlans < ActiveRecord::Migration[5.0]
def change
add_column :spree_plans, :points, :integer
end
end
|
module Charts
class IssueList
prepend SimpleCommand
IssueInfo = Struct.new(:id, :issue_no, :cultivation_batch_id, :severity, :c_at, :status, :title, :batch_no)
def initialize(current_user, args = {})
@user = current_user
@args = args
@facility_id = @args[:facility_id].split(',').map { ... |
class CreateTracklists < ActiveRecord::Migration[6.1]
def change
create_table :tracklists do |t|
t.string :name, :null => false
t.date :date_played, :null => false
t.references :artist, :null => false, :foreign_key => true
t.string :youtube_url
# TODO Check the alias of creator to us... |
require 'spec_helper'
describe Praxis::MediaType do
let(:owner_resource) { instance_double(Person, id: 100, name: /[:name:]/.gen, href: '/', links: ['one','two']) }
let(:manager_resource) { instance_double(Person, id: 101, name: /[:name:]/.gen, href: '/', links: []) }
let(:resource) do
double('address', id:... |
class User < ApplicationRecord
has_many :tweets, dependent: :destroy
has_many :likes, dependent: :destroy
has_many :liked_tweets, through: :likes, source: :tweet
has_one_attached :avatar
validates :name, :username, presence: true
validates :username, uniqueness: true
enum role: { member: 0, admin: 1 }
... |
Rails.application.routes.draw do
devise_for :users
root to: "workschedules#index"
get 'workschedules/index'
resources :workschedules
end
|
require_relative 'models_helper'
describe User do
before do
@user = User.new('Reginald', 'Fartswaith')
end
describe 'name convenience method' do
it 'should return first and last names' do
@user.name.should match 'Reginald Fartswaith'
end
end
end |
Factory.sequence(:email) {|n| "person#{n}@example.com" }
Factory.define :user do |user|
#user.email "bigmac@example.com"
user.email { Factory.next :email }
user.password "foobar"
user.password_confirmation "foobar"
end
Factory.define :cluster do |cluster|
cluster... |
require 'test_helper'
class PlaguesControllerTest < ActionDispatch::IntegrationTest
setup do
@plague = plagues(:one)
end
test "should get index" do
get plagues_url
assert_response :success
end
test "should get new" do
get new_plague_url
assert_response :success
end
test "should cre... |
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
#현재 로그인 된 상태니?
helper_method :user_signed_in?
def user_signed_in?
!session[:current_user].nil?
end
#로그인이 되어있지 않으면 로그인하는 페이지로 이동 시켜줘
def authenticate_user!
unless user_signed_in?
redirect_to ... |
json.array!(@hierarchies) do |hierarchy|
json.extract! hierarchy, :p_id, :gname
json.url hierarchy_url(hierarchy, format: :json)
end
|
module Wizardry
module Questions
# Ask a question that can be answered with multiple lines of text
class LongAnswer < Wizardry::Questions::Answer
def initialize(name)
Rails.logger.debug("🧙 Adding long question '#{name}'")
super
end
def form_method
:govuk_text_area
... |
pg_ver = input('pg_version')
pg_dba = input('pg_dba')
pg_dba_password = input('pg_dba_password',)
pg_db = input('pg_db')
pg_host = input('pg_host')
pg_max_connections = input('pg_max_connections')
control "V-72863" do
title "PostgreSQL must limit the number of concurrent sessions to an
organization-defined nu... |
module ListingsHelper
WillPaginate.per_page = 10
def tag_links(tags)
tags.titleize.split(",").map{|tag| link_to tag.strip, tag_path(tag.strip) }.join(", ")
end
end
|
class CreateAids < ActiveRecord::Migration
def change
create_table :aids do |t|
t.datetime :sent_date
t.integer :sender_id
t.string :sender_alliance
t.string :sender_name
t.integer :recipient_id
t.string :recipient_alliance
t.string :recipient_name
t.integer :money
... |
Capybara.add_selector(:select_button) do
xpath do |locator, _options|
translated = ET3::Test::Messaging.instance.translate(locator)
XPath.generate { |x| x.css('.button.button-secondary') }
end
end
|
module Gradebook
module Reports
class Template
# Template.config do
# name 'template_1'
# target_type :school
# schools [11,22]
#
# setting do
# name 'logo'
# type :hash # :text, :hash, :array
# options {'cbse' => assets_path + "cbselogo.j... |
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
include SessionsHelper
#Confirms a logged-in user.
def logged_in_user
unless logged_in?
render json: { error: 'Log in to access this page'}, status: :unauthorized
end
end
end
|
class AddTypeToStylist < ActiveRecord::Migration
def change
add_column :stylists, :type, :string
end
end
|
class DiaryEntry < ActiveRecord::Base
attr_accessible :title, :description, :mood
def self.positive
where(mood: ["happy", "joyful"])
end
validates :description, presence: true
validates :title, presence: true, uniqueness: true
end |
require 'rails_helper'
RSpec.describe "processors/index", type: :view do
before(:each) do
assign(:processors, [
Processor.create!(),
Processor.create!()
])
end
it "renders a list of processors" do
render
end
end
|
class ProductsController < ApplicationController
before_action :fetch_product, only: [:show, :edit, :update, :destroy,
:toggle_featured]
def index
@products = Product.all
respond_to do |format|
format.html
format.json { render json: @products }
end
end
def show
respond_to do |... |
require "spec_helper"
describe DiscountNetwork::Configuration do
describe ".configuration" do
it "returns the client configuraiton object" do
api_host = "https://api.discountnetwork.io/api/v1"
configuration = DiscountNetwork.configuration
expect(configuration.api_host).to eq(api_host)
end
... |
FactoryBot.define do
factory :plate do
sequence(:name) {|n| " name #{n}" }
main_ingredient { "MyString" }
type_plate { "MyString" }
price { 1.5 }
comment { "MyString" }
trait :invalid do
name { nil }
end
trait :new_name do
name { 'New plate' }
end
end
end
|
class Subject
attr_accessor :name, :score
def initialize(name, score)
@name = name
@score = score
end
def getSubjectMessage
"科目:#{@name},成绩:#{@score}"
end
end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.