text
stringlengths
10
2.61M
module Apotomo # Methods needed to serialize the widget tree and back. module Persistence def self.included(base) base.extend(ClassMethods) end # For Ruby 1.8/1.9 compatibility. def symbolized_instance_variables instance_variables.map { |ivar| ivar.to_sym } end def free...
class Event < ActiveRecord::Base # include helper module for query caching include Cacheable # include event processing include Processable # include doi normalization include Identifiable # include helper module for Elasticsearch include Indexable include Elasticsearch::Model before_validation...
module Erp class ApplicationMailer < ActionMailer::Base default from: "soft.support@hoangkhang.com.vn" layout 'mailer' private def send_email(email, subject) #@todo static email!! delivery_options = { address: 'smtp.gmail.com', port: 587, domain: 'global...
# $LICENSE # Copyright 2013-2014 Spotify AB. All rights reserved. # # The contents of this file are 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-...
require 'rails_helper' describe ReviewsController do let(:valid_attributes) { attributes_for :review } let(:invalid_attributes) { attributes_for :review, msg: "" } describe "GET #index" do it "assigns all reviews as @reviews" do review = Review.create! valid_attributes get :index, {} expe...
# -*- encoding : utf-8 -*- class ConfigAppsController < ApplicationController load_and_authorize_resource #cancan def show @config_app = ConfigApp.find(params[:id]) end def index @config_app= ConfigApp.all respond_to do |format| format.html format.js end end def new ...
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable # Setup accessi...
require 'minitest/autorun' require 'minitest/reporters' require 'minitest/skip_dsl' # TODO: uncomment the next line once you start wave 3 and add lib/checking_account.rb require_relative '../lib/checking_account' # Because a CheckingAccount is a kind # of Account, and we've already tested a bunch of functionality # o...
# Создайте класс JellyBean, # расширяющий класс Dessert (из Упражнения 11) # новыми геттерами и сеттерами для атрибута flavor. # Измените метод delicious? таким образом, # чтобы он возвращал false только в тех случаях, # когда flavor равняется «black licorice». require_relative 'task_11.rb' class JellyBean <...
require 'vizier/registry' require 'vizier/dsl/argument' require 'vizier/task/base' module Vizier class << self def describe_commands(name=nil, &block) calling_file = CommandDescription.get_caller_file name ||= File::basename(calling_file, ".rb") CommandDescription.command(name, calling_file, &bl...
class FunctionCostCenter < ActiveRecord::Base belongs_to :function belongs_to :cost_center end
module Sources class ArsSecurity extend CD::RssParser def self.parse get_feed('https://feeds.feedburner.com/arstechnica/technology-lab?format=xml') do |xml| parse_feed(xml) do |item| { title: item.at('title').text, description: CGI.escape_html(item.at('descrip...
class CreateParts < ActiveRecord::Migration def change create_table :parts do |t| t.integer :vendor_id t.integer :part_category_id t.string :article t.string :title t.string :dimension t.decimal :buy_price t.decimal :margin t.integer :sell_price t.timestamps ...
require_relative 'db_connection' require_relative 'errors' require_relative 'exceptions' require_relative 'core_extension' require 'active_support/inflector' # NB: the attr_accessor we wrote in phase 0 is NOT used in the rest # of this project. It was only a warm up. class SQLObject attr_reader :errors def self.c...
require 'capistrano' module Capistrano::Fanfare::DatabaseYaml def self.load_into(configuration) configuration.load do # ========================================================================= # These are the tasks that are available to help with deploying web apps. # You can have cap give you...
module StudioGame class Die # create initial state of die and call its roll method upon creation def initialize roll end # returns a random number between 1 and 6 def roll @number = rand(1..6) end end # put file-specific example code here if __FILE__ == $0 number_roll...
describe BookmarkTag do describe '.create' do it 'adds a BookmarkTag to the database' do bookmark = Bookmark.create(title: 'Goal', url: 'http://www.goal.com') tag = Tag.create(content: 'football') bookmark_tag = BookmarkTag.create(bookmark_id: bookmark.id, tag_id: tag.id) expect(boo...
class User < ActiveRecord::Base has_many :feedbacks # NEW LINE - Indicates association with Micropost belongs_to :course before_save do |user| user.email = email.downcase user.remember_token = SecureRandom.urlsafe_base64 end # End of replacement validates :name...
# # Cookbook Name:: configure_nginx # Recipe:: default # # Copyright (c) 2015 The Authors, All Rights Reserved. default_path = "/etc/nginx/sites-enabled/default" execute "rm -f #{default_path}" do only_if { File.exists?(default_path) } end template "/etc/nginx/sites-enabled/current" do source "nginx.conf.erb" m...
#!/usr/bin/ruby # read pianobar configuration for user email config = File.readlines("#{ENV['XDG_CONFIG_HOME']}/pianobar/config") begin email = config.grep(/^\s*user/).first.split("=")[1].strip rescue warn "Email needs to be configured in your pianobar configuration." exit 1 end # pass along the email to gnome-...
require 'date' class UsersController < ApplicationController def index @users = User.all end def create_user @user = User.new end def login @user = User.find_by(username: params[:username]) if @user session[:username] = @user.id flash[:success] = "#{ @user.username } is success...
require 'spec_helper' describe MessageCenter::Notification, :type => :model do before do @entity1 = FactoryGirl.create(:user) @entity2 = FactoryGirl.create(:user) @entity3 = FactoryGirl.create(:user) end it { is_expected.to validate_presence_of :subject } it { is_expected.to validate_presence_of ...
require 'rails_helper' RSpec.describe List, type: :model do it{ should belong_to :user } it{ should have_many :remarks } it{ should have_many :confirms } it{ should validate_presence_of :title } it{ should validate_presence_of :body } end
FactoryBot.define do factory :equipment do equipment_name attack_strength { Random.rand(Equipment::ATTACK_RANGE) } defense_strength { attack_strength.zero? ? Random.rand(1..Equipment::MAX_DEFENSE) : 0 } factory :weapon do attack_strength { Random.rand(1..Equipment::MAX_ATTACK) } defense_...
# frozen_string_literal: true FactoryBot.define do factory :property do sequence(:property_name) { |i| "Some Property Name #{i}" } property_address { 'Some Property Address' } landlord_first_name { 'Some Landlord Address' } landlord_last_name { 'Some Landlord Last Name' } sequence(:landlord_email...
class StoriesController < ApplicationController before_action :get_root, :get_story @root def show end def get_story @story = @root.get_story(params[:id]) @story_characters = @root.get_story_characters(@story.first["id"]) end def get_root @root ||= Root.new end end
class TextblocksController < ApplicationController before_filter :login_required, :except => [ :show, :short, :frontpage ] def index list render :action => 'list' end def list @textblock_pages, @textblocks = paginate :textblocks, :per_page => 25 end def search if !params['criteria'] || ...
require_relative "#{App.root}/app/models/color.rb" require_relative "#{App.root}/app/models/substance.rb" class TestKit < Dry::Struct attribute :name, Types::Strict::String attribute :color, Types.Instance(Color) end
#This application runs in order to convert the IRDS dashboard data from csv to xls class CSVConverter require 'csv' require 'spreadsheet' require 'sudo' def initialize p "Initialize converter..." @counter = 0 read_write_save_file end def read_write_save_file p "Createing New Spreadsheet" book = Sp...
require 'test_helper' describe ShallowAttributes::Type::DateTime do let(:type) { ShallowAttributes::Type::DateTime.new } describe '#coerce' do describe 'when value is DateTime' do it 'returns date time object' do time = DateTime.now type.coerce(time).must_equal time end end ...
require 'helper' require 'deviantart' require 'deviantart/authorization_code' require 'deviantart/authorization_code/refresh_token' require 'deviantart/client_credentials/access_token' class DeviantArt::Client::Test < Test::Unit::TestCase sub_test_case '#refresh_access_token with Authorization Code Grant' do set...
class ItemsController < ApplicationController def index @items = Item.all end def show @item = Item.find(params[:id]) end def new @item = Item.new end def create @item = Item.create(item_params) @item.save redirect_to @item end private def item_params params.require(:item).permit(:name, :descrip...
require 'spec_helper' describe MassMigrator do subject { MassMigrator.new(/^mentions_client_3$/, :db => $db) } def table_columns(table_name) $db.schema(table_name, :reload => true).map {|(column, data)| column } end let!(:migration_class) do Class.new(MassMigrator::Migration) do def up ...
# frozen_string_literal: true module Mutations class UpdateMe < ::Mutations::BaseMutation description 'カレントユーザー情報更新' argument :name, ::String, required: false field :current_user, ::Types::Objects::CurrentUserObject, null: true def mutate(name:) context[:current_info][:user].update!(name: na...
class Baraja attr_reader :cartas def initialize(*cartas) @cartas = *cartas end def numero_de_cartas @cartas.length end def contiene_carta?(c) @cartas.include?(c) end def add_carta(c) @cartas += [ c ] end def self.completa mazo = [] Carta.palos.each do |palo| (1..12).each do |valor| m...
require 'delegate' require 'active_support/core_ext/module/delegation' require 'active_support/core_ext/object/blank' require 'active_model/naming' require 'hydramata/works/conversions/translation_key_fragment' require 'hydramata/works/conversions/presenter' module Hydramata module Works # Responsible for wrappi...
class AppointmentRequestMailer < ApplicationMailer default from: 'community.cares.boulder@gmail.com' def appointment_request_confirmation_email(appointment_request) @appointment_request = appointment_request #@url = 'https://community-cares-iansharp93.c9.io/appointment_request' mail...
require './test_helper' require './lib/sales_engine' require './lib/transaction_repository' require 'bigdecimal' class TransactionRepositoryTest < MiniTest::Test def setup se = SalesEngine.from_csv({ :items => "./data/mock.csv", :merchants => "./data/mock.csv", :invoices => "./data/mock.csv", ...
require 'rails_helper' RSpec.describe CheckinsHelper, type: :helper do describe '#date_labels' do it 'returns last 10 days' do expect(helper.date_labels.count).to eq 10 expect(helper.date_labels.last).to eq Date.today.strftime(DATE_FORMAT) end end describe '#checkin_times' do let(:hour_i...
#!/usr/bin/env ruby require 'csv' require 'awesome_print' require 'json' class Splitter def initialize(source, target, key) @source = source @target = target @key = key values = readCSV(@source) splitted = values.group_by do |item| item[key] end ap splitted splitted.each do |...
require 'spec_helper' describe DataLink do let(:user) { User.make! } context "DataLink creation" do before(:all) do @deployment = given_resources_for([:deployment], :user => user)[:deployment] end it "should be invalid without a user, deployment and sourcable" do data_link = DataLink.new(...
require 'snippetize/version' require 'snippetize/snippet' require 'snippetize/action_view_extensions/snippetize_helper' module Snippetize mattr_accessor :location @@location = 'snippets' def self.setup yield self end end
# 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 bin/rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # ...
# encoding: utf-8 # Inspec test for recipe jnj_chef_stack::workflow_builder # The Inspec reference, with examples and extensive documentation, can be # found at https://docs.chef.io/inspec_reference.html packages = %w(chefdk) packages.each do |p| describe package(p) do it { should be_installed } end end dir...
module RubyKongAuth class Model def initialize(attributes) attributes.each do |key, value| send("#{key.to_s}=", value) rescue false end end def instance_values Hash[instance_variables.map { |name| [name[1..-1], instance_variable_get(name)] }] end def to_sym self.i...
class Vehicle < ActiveRecord::Base belongs_to :customer before_save { self.vehicle_no =vehicle_no.upcase} validates :vehicle_no, uniqueness: { case_sensitive: false} validates_format_of :vehicle_no, :with => /\A^[A-Za-z]{2}[a-zA-Z0-9]{3,}$\z/, messages: "Invalid Vehcile Number format" vali...
module Spree class TemplateText < ActiveRecord::Base validates_presence_of :name attr_accessible :name, :body #for resource_class.resourceful scope :resourceful, ->(theme){ where("1=1") } default_scope ->{ where(:site_id=>Site.current.id)} end end
module Fog module Compute class Google ## # Represents a Region resource # # @see https://developers.google.com/compute/docs/reference/latest/regions class Region < Fog::Model identity :name attribute :kind attribute :id attribute :creation_timestamp,...
#rake db:test:prepare Given /^I am on the "([^"]*) ([^"]*)" page$/ do |action,controller| visit("/#{controller.downcase}s/#{action.downcase}") end When /^I submit a purchase called "([^"]*)" that costs "([^"]*)"$/ do |purchase,cost| fill_in 'Purchase', :with => purchase fill_in 'Cost', :with => cost click_but...
# frozen_string_literal: true module Relax module SVG module Structural # Structural element as defined by # https://www.w3.org/TR/SVG2/struct.html#GElement class Group < Relax::SVG::Structural::StructuralPrototype NAME = 'g' GEOMETRY_ATTRIBUTES = %i[x y width height].freeze ...
require 'rails_helper' RSpec.shared_examples_for Contact do describe '#prepares_for_form' do it 'prepares address' do contactable = described_class.new expect(contactable.address).to be_nil contactable.prepare_for_form expect(contactable.address).not_to be_nil end it '#clear_up_f...
## # Copyright 2017-2018 Bryan T. Meyers # # 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 to in w...
class StoriesController < ApplicationController include ChapterExtension include AdventurerExtension # before_filter :authenticate_user!, except: [:prelude, :read, :search, :index] # load_and_authorize_resource except: [:prelude, :read] before_filter :authenticate_user!, except: [:search_result, :detail] l...
class User < ActiveRecord::Base has_many :shouts include Clearance::User end
# # Copyright 2009 Huygens Instituut for the History of the Netherlands, Den Haag, The Netherlands. # # This file is part of New Women Writers. # # New Women Writers is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundat...
module Deployinator module Stacks module Twbt def uat_version %x{ssh deploy@pitch160.anchor.net.au cat /home/deploy/apps/uat_12wbt/current/REVISION | cut -c1-7} end def prod_version %x{ssh deploy@martingale.anchor.net.au cat /home/deploy/apps/12wbt/current/REVISION | cut -c1-7}...
class Pwb::Devise::RegistrationsController < Devise::RegistrationsController def edit_success return render "/devise/registrations/edit_success" end # The default url to be used after updating a resource. You need to overwrite # this method in your own RegistrationsController. def after_update_path_for(...
class ProductoTrabajo < ActiveRecord::Base attr_accessible :detalle validates :detalle, :presence => true end
class Subreddit < ApplicationRecord def self.update_list(subreddit_array) return if subreddit_array.blank? Subreddit.delete_all subreddit_array.each do |com| next if com.to_s.strip.blank? s = Subreddit.new s.subreddit_name = com s.save! end end end
# Permission class model class Permission < ActiveRecord::Base has_many :user_permissions has_many :users, through: :user_permissions, dependent: :destroy has_many :role_permissions has_many :roles, through: :role_permissions, dependent: :destroy name_message = 'permission must have a unique name' name_len...
module UsersHelper include Rack::Recaptcha::Helpers # TODO cache these def user_avatar(user, size="150x150#") return "" if user.avatar.blank? image_tag(user.avatar.thumb(size).url, class: 'avatar', alt: user.username ).html_safe end def user_avatar_small(user) user_avatar(user,...
class Identity < ActiveRecord::Base #t.string :name #t.string :password_digest validates :name, presence: true, uniqueness:true validates :password, length: {minimum: 6} has_secure_password has_one :user end
class AddSocialLinksToCoaches < ActiveRecord::Migration[5.0] def change add_column :coaches, :website, :string add_column :coaches, :facebook, :string add_column :coaches, :instagram, :string add_column :coaches, :youtube, :string add_column :coaches, :twitter, :string add_column :coaches, :li...
module Spree module Concerns module Indexable class ResultList include Enumerable attr_accessor :results attr_accessor :total attr_accessor :from def initialize(results, from, total) self.results = results self.from = from self.total = ...
class ThemesController < ApplicationController def random category = Category.find(params[:category_id]) @theme = category.themes.all.sample end end
require 'main/resources/v1/recipe_pb' require 'google/protobuf/well_known_types' class Recipe < ApplicationRecord belongs_to :user has_many :ingredients, -> { order(:position) }, dependent: :destroy has_many :steps, -> { order(:position) }, dependent: :destroy validates :title, presence: true validates :des...
# ========================================================================== # Project: Lebowski Framework - The SproutCore Test Automation Framework # License: Licensed under MIT license (see License.txt) # ========================================================================== module Lebowski module Foundat...
require_relative '../lib/dwelling' require_relative '../lib/occupant' require_relative '../lib/modules' class Apartment < Dwelling include Modules attr_reader :address, :city_or_town, :zip_code, :rent, :lease_start_date, :lease_end_date, :space, :objects def initialize(address, city_or_town, zip_code, rent, lea...
require 'generators/feature_box/generator_base' module FeatureBox module Generators class ExistingGenerator < Rails::Generators::NamedBase include GeneratorBase desc "Installs FeatureBox to existing application" def feature_box_install #name of the User model @model_name = fi...
class CreateEmployeeTeams < ActiveRecord::Migration def change create_table :employee_teams do |t| t.integer :team_id t.integer :employee_id t.timestamps null: false end add_index :employee_teams, [:team_id, :employee_id], :unique => true end end
class OrderItemsController < ApplicationController skip_before_action :require_login # before_action :set_order, only: [:ship] def create product = Product.find_by(id: params[:order_item][:product_id]) if params[:order_item][:qty].to_i > product.inv_qty flash[:warning] = "Quantity selected exceeds...
require 'rubygems' require 'nokogiri' require 'resx_template' ROOT_DIR = 'c:/Andrew/IBA/GDYR/MESPOD/SVN_HG/MESPOD/' TO_TRANSLATE_CSV = '../../MessagesToTranslate.csv' TRANSLATED_CSV = '../../TranslatedMessages.csv' TO_TRANSLATE_CSV_MERGED = 'MessagesToTranslate_merged.csv' def resources_to_csv Dir::chdir...
#!/usr/bin/env ruby require './board' require 'yaml' class MinesweeperGame def initialize mode = choose_mode @board = Board.new(mode) @accum_time = 0 end def play_game @start_time = Time.now until @board.game_over? play_turn end @accum_time += Time.now - @start_time @board...
module Peano def Recur(&block) Trampoline.run(block) end class Trampoline def run(&block) result = block.call while result.kind_of?(Proc) do result = result.call end result end end end
class MissingRelations < ActiveRecord::Migration def change create_table :resellers_products do |t| t.integer :reseller_id t.integer :products_id end create_table :events_partners do |t| t.integer :event_id t.integer :partner_id end add_column :products, :partner_id, :int...
Pod::Spec.new do |s| s.name = 'PSPDFKit' s.version = '10.1.0' s.homepage = 'https://pspdfkit.com' s.documentation_url = 'https://pspdfkit.com/guides/ios/current' s.license = { :type => 'Commercial', :file => 'PSPDFKit.xcframework/LICENSE' } s.author ...
class Admin::CandidateProfilesController < ApplicationController before_action :authenticate_user! layout 'admin' def index @candidate_profiles = CandidateProfile.order(created_at: :desc) end def show @candidate_profile = CandidateProfile.find(params[:id]) end end
class AddAreaToTranslationCacheMetaData < ActiveRecord::Migration[5.0] def change add_column :translation_cache_meta_data, :area, :string, default: 'dresden' end end
class Membership < ActiveRecord::Base include ActiveModel::Transitions belongs_to :user belongs_to :company validates_presence_of :status state_machine attribute_name: :status do state :active end end
namespace :dev do desc "Configure development environment" task setup: :environment do p 'Generating new database' %x(rails db:drop db:create db:migrate) p 'Creating Users...' 10.times do |user| User.create!( email: Faker::Internet.email, password: '123456' ) end ...
require 'spec_helper' # describe OurOneFeature do describe 'a random user visits the home page' do it 'should have a field for a user name' do visit root_path expect(page).to have_field('username') end it 'should have a button to show picture' do visit root_path expect(page).to h...
class BroProductImage < ActiveRecord::Base belongs_to :product, class_name: 'BroProduct', foreign_key: 'bro_product_id', touch: true has_one :bro_sale, through: :product mount_uploader :file, BasicUploader mount_uploader :thumbnail, BasicUploader scope :sorted, -> { order(position: :asc) } end
require 'spec_helper' describe RouteLocalize do let(:args) { [app, conditions, requirements, defaults, as, anchor, route_set] } let(:app) { double(:app) } let(:conditions) { { required_defaults: [:localize], path_info: "/bang" } } let(:requirements) { [:localize] } let(:defaults) { {} } let(:as) { "bang" }...
class UsersController < ApplicationController def index @users = params[:ids] ? User.where(id: params[:ids].split(",")).to_a : User.all.to_a end def create_or_replace if user = User.find_by( id: params[:id] ) replacement= User.new( user_params.merge( id: params[:id] ) ...
class Api::V1::AboutmesController < Api::V1::BaseController def index user = current_user aboutme = user.aboutme render json: aboutme, status: 200 end end
require 'rails_helper' RSpec.describe 'Merchants Show API' do before :each do FactoryBot.reload end describe 'happy path' do it 'fetch one merchant by id' do merchant1 = create(:merchant) get "/api/v1/merchants/#{merchant1.id}" expect(response).to be_successful merchant = JSON.p...
# The model has already been created by the framework, and extends Rhom::RhomObject # You can add more methods here require 'json' class Product include Rhom::PropertyBag # Uncomment the following line to enable sync with Product. # enable :sync property :name, :string property :brand, :string property...
class Role < ApplicationRecord has_many :research_users has_many :users, through: :research_users validates :name, presence: { message: "Nombre no puede ir vacio" }, uniqueness: { case_sensitive: false, message: "Ya hay otro rol con el mismo nombre" } def self.get_default_role where(is_d...
require 'spec_helper' RSpec.describe Role do it { is_expected.to belong_to(:team) } it { is_expected.to belong_to(:user) } it { is_expected.to validate_presence_of(:user) } it { is_expected.to validate_presence_of(:name) } it { is_expected.to validate_inclusion_of(:name).in_array(Role::ROLES) } it { is_exp...
class Post < ActiveRecord::Base has_many :comments, dependent: :destroy has_many :images, dependent: :destroy validates :title, presence: true validates :text, presence: true validates :author, presence: true accepts_nested_attributes_for :images, reject_if: proc { |attributes| attributes["filename"].bla...
class Order < ApplicationRecord # belongs_to :account has_many :order_items before_save :update_total before_create :update_status def calculate_total self.order_items.collect { |item| item.product.price * item.quantity }.sum end def total_items self.order_items.collect { |item| item.quantity }....
module StyleGuide class JavaScript < Base DEFAULT_CONFIG_FILENAME = "javascript.json" def file_review(commit_file) FileReview.new(filename: commit_file.filename) do |file_review| Jshintrb.lint(commit_file.content, config).compact.each do |violation| line = commit_file.line_at(violatio...
require 'set' class Character < ApplicationRecord has_and_belongs_to_many :story belongs_to :user has_many :relationships has_many :follower_relationships, foreign_key: :character2, class_name: 'Relationship' has_many :followers, through: :follower_relationships, source: :follower has_many :following_...
# 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...
module MacRubyScreencastsHelper Screencast = Struct.new(:date, :name, :href, :author, :company) def macruby_screencasts [ Screencast.new("2010-04-10", "Introduction to MacRuby and HotCocoa", "http://thinkcode.tv/catalog/introduction-macruby/", "Renzo Borgatti", "ThinkCode.TV"), Screencast.new(...
require 'active_support/core_ext/string' require 'builder' module OWD class Document def initialize attributes = {} @attributes = attributes @doc = Builder::XmlMarkup.new end def owd_name "OWD_%s_REQUEST" % self.class.name.split('::').last.underscore.upcase end def buil...
# question_9.rb flintstones = { "Fred" => 0, "Wilma" => 1, "Barney" => 2, "Betty" => 3, "BamBam" => 4, "Pebbles" => 5 } # There are two elements to this # 1. Removing all the key value pairs except for "Barney" => 2 # 2. Changing the resulting hash into an array # For the first part we could use keep_if or select an...
class Api::BooksController < ApplicationController before_action :require_signed_in! def reviews @book = Book.find(params[:id]) render :reviews end def create isbn = book_params['isbn'] @book = Book.find_by_isbn(isbn) if @book render :show else @book = Book.new(book_params)...
class BootstrapAttributeTableResourceRenderer < AttributeTableResourceRenderer private def table_html_options { class: 'table table-responsive table-condensed table-striped table-hover' } end end
RSpec.configure do |config| config.before(:all, type: :request) do host! 'api.example.com' end end module RequestHelpers def json_headers { 'Accept' => 'application/json', 'Content-Type' => 'application/json', } end def json return if response.body.blank? Oj.load(response.bod...