text
stringlengths
10
2.61M
class I0020 attr_reader :title, :options, :name, :field_type, :node def initialize @title = "Section I: Active Diagnoses" @name = "Indicate the resident's primary medical condition category. (Complete only if A0310b = 01 or 08) (I0020)" @field_type = DROPDOWN @node = "I0020" @options = [] ...
class QuestionsController < ApplicationController def index @questions = Question.all end def show @question = Question.find(params[:id]) if !logged_in flash.now[:warning] = "You cannot answer a question unless you are logged in!" elsif !Answered.find_by(questionID: @question.id, teamID: c...
# rubocop: disable Metrics/ParameterLists def property_new \ id: nil, human_ref: 2002, occupiers: [Entity.new(title: 'Mr', initials: 'W G', name: 'Grace')], address: address_new, account: nil, client: client_new, agent: nil, prepare: false property = Property.new id: id, human_ref: human_ref prope...
# == Schema Information # # Table name: all_jokes # # id :bigint(8) not null, primary key # joke :string # joke_type :integer # sequence :integer # uuid :integer # created_at :datetime not null # updated_at :datetime not null # require 'rails_helper' RSpec.describe...
class AccountCodesController < ApplicationController def destroy @project = current_user.owned_projects.find(params[:project_id]) ids = SuretyMember.where(surety_id: @project.surety_ids).pluck(:account_code_id) ac = AccountCode.where(id: ids).find(params[:id]) ac.destroy redirect_to @project end...
class AddColumnRucAndAddressToWorkPartners < ActiveRecord::Migration def change add_column :work_partners, :ruc, :string add_column :work_partners, :address, :text end end
module Wallet class Credit < ApplicationRecord belongs_to :account, class_name: "Wallet::Account", foreign_key: "wallet_account_id" end end
class User::Customer < User has_many :tickets, foreign_key: :customer_id has_many :messages, foreign_key: :customer_id end
class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable enum role: { user: 0, admin: 1, provider: 2, manager: ...
# Class to create an inventory record # We're using class 6 to create getters and setters # getters just get the data from the class # We write getters and setters for the size array because we don't want to expose to the outside world that we are using an array # remeber that getters return what is being asked for, a...
class RPagesController < ApplicationController before_action :set_r_page, only: [:show, :edit, :update, :destroy] # GET /r_pages # GET /r_pages.json def index @r_pages = RPage.all end # GET /r_pages/1 # GET /r_pages/1.json def show end # GET /r_pages/new def new @r_page = RPage.new en...
class Player attr_accessor :cards, :amount attr_reader :name def initialize(name, amount) @name = name @amount = amount @cards = [] end end
Vagrant.configure("2") do |config| # Run `vagrant rsync-auto` to sync the shared directory automatically config.vm.synced_folder "..", "/vagrant", type: "rsync" config.vm.define "main" do |main| main.vm.box = "ubuntu/xenial64" main.vm.network "private_network", ip: "10.10.10.10" main.vm.hostname = "...
class Follow < ApplicationRecord # Direct associations belongs_to :stock, :counter_cache => true belongs_to :user # Indirect associations # Validations validates :stock_id, :uniqueness => { :scope => [:user_id], :message => "already liked" } validates :stock_id, :presence => true val...
require_relative "lib/lorem_ipsum_nearby/version" Gem::Specification.new do |spec| spec.name = "lorem_ipsum_nearby" spec.version = LoremIpsumNearby::VERSION spec.authors = ["A T M Hassan Uzzaman"] spec.email = ["sajib.hassan@gmail.com"] spec.summary = "This is a gem for a Tech challenge" spec.description ...
module MTMD module FamilyCookBook module Search class RecipeByIngredient < ::MTMD::FamilyCookBook::Search::Recipe def query(phrase) MTMD::FamilyCookBook::Recipe. where( :id => MTMD::FamilyCookBook::Ingredient. association_join(:ingredient_quantiti...
class AddAndRemoveFieldsToSite < ActiveRecord::Migration def change add_column :sites, :status, :string add_column :sites, :contact_name, :string add_column :sites, :contact_phone, :string add_column :sites, :contact_phone_ext, :string add_column :sites, :contact_email, :string remove_column ...
require 'hotel_beds/parser' require 'hotel_beds/parser/cancellation_policy' require 'hotel_beds/parser/price' require 'hotel_beds/parser/customer' require 'hotel_beds/parser/tax' module HotelBeds module Parser class AvailableRoom include HotelBeds::Parser # attributes attribute :id, selector: ...
require 'money' require_relative '../../../lib/customers/customer' require_relative '../../../lib/customers/card' require_relative '../../../lib/supervisor' require_relative '../../../lib/payments/transactions/transaction' require_relative '../../../lib/event_handler' require_relative '../../../lib/payments/transaction...
class FBCredentialsProvider < Facebook::Messenger::Configuration::Providers::Base def valid_verify_token?(verify_token) verify_token == ENV['FB_MESSENGER_VERIFY_TOKEN'] end def app_secret_for(*) ENV['FB_MESSENGER_APP_SECRET'] end def access_token_for(*) ENV['FB_MESSENGER_ACCESS_TOKEN'] end end...
# frozen_string_literal: true module Validations def self.included(base) base.extend ClassMethods base.send :include, InstanceMethods end # rubocop:disable Metrics/MethodLength # rubocop:disable Metrics/LineLength # rubocop:disable Metrics/AbcSize # rubocop:disable Metrics/CyclomaticComplexity m...
# frozen_string_literal: true # rubocop:todo all # Copyright (C) 2014-2020 MongoDB 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 # # U...
require 'poke' def game(pokes) possible_board = pokes.combination(5).to_a possible_board.map {|board| compute_result(board)}.min end def compute_result(pokes) duplicate_cards_sort = duplicate_cards(pokes).values.sort flush = flush?(pokes) straight = straight?(pokes) has_max_card = has_max_card?(pokes) ...
class Favourite < ActiveRecord::Base # Associations belongs_to :user belongs_to :work # Checks if user has already favourited the work once. validate :user_has_not_favourited_work # Check if the user has already favourited the work before and throw an error if so def user_has_not_favourited_work er...
class Sport < ApplicationRecord has_attachment :photo has_many :events, inverse_of: :sport has_many :favorite_sports has_many :users, through: :favorite_sports validates :name, presence: true validates :name, uniqueness: true end
class Comment < ApplicationRecord belongs_to :post validates :nickname, presence: true validates :body, presence: true end
# Require dependencies. # sinatra - lightweight web framework # json - for JSON marshalling. require 'sinatra' require 'json' require 'securerandom' # Setup const for json content type. JSON_CONTENT_TYPE = 'application/json' # Methods needed for / endpoint. # This tells the API server what endpoints are available # t...
require "fileutils" if ENV['random'] random_dir = File.expand_path ENV['random'] unless File.directory?(random_dir) $stderr.puts "Unable to find source directory #{random_dir}" exit 1 end candidates = Dir[random_dir + "/**/*.wav"].shuffle unless candidates.size > 1 $stderr.puts "Source directory ...
require 'spec_helper' require 'yt/errors/forbidden' describe Yt::Errors::Forbidden do let(:msg) { %r{^A request to YouTube API was considered forbidden by the server} } describe '#exception' do it { expect{raise Yt::Errors::Forbidden}.to raise_error msg } end end
# Course controller class CoursesController < ApplicationController before_action :find_course, except: %w[index new create] before_action :find_instructors, only: %w[new edit] def index @courses = policy_scope(Course) authorize @courses end def new @course = Course.new authorize @course e...
class OrganizationsController < ApplicationController def show @organizations = Organization.find(params[:id]) end end
class Item < ActiveRecord::Base belongs_to :sale belongs_to :scheduled_delivery belongs_to :delivery after_create :reload validates_presence_of :model, :serial, :brand scope :sold, -> { where(sold: true) } scope :unsold, -> { where(sold: false) } def address scheduled_delivery.address end d...
module PageHelper def footer_images (Dir.entries("./app/assets/images/footer") - [".", ".."]).shuffle[0..3] end def napi_images(page) (Dir.entries("./app/assets/images/napi") - [".", ".."])[(page-1)*10...(page)*10] end def name_list [{:home => "Home"}, {:about=> "History", :past=>"Past...
require "spec_helper.rb" describe "Deleting todo_item" do let!(:todo_list) {TodoList.create(title: "Grocery list", description: "Groceries")} let!(:todo_item) {todo_list.todo_items.create(content: "Milk")} def delete_todo_item within(dom_id_for(todo_item)) do click_link "Delete" ...
#Magic 8-Ball ##Objective #Use methods to keep our code DRY. ##Instructions #Build a ruby program that when run will ask the user if they want to shake the eight ball. #If the user answers yes, have it give a random message. #If the user says no, have it end. class Eightball def initialize @messages = [ "It i...
require 'goby' module Goby # Can be worn in the Player's outfit. class Shield < Item include Equippable # @param [String] name the name. # @param [Integer] price the cost in a shop. # @param [Boolean] consumable upon use, the item is lost when true. # @param [Boolean] disposable allowed to sell or dr...
require 'RSpec' require_relative '../lexiconomitron.rb' RSpec.describe "Lexiconomitron" do describe "#eat_t" do it "returns the same string if there is no t" do @lexi = Lexiconomitron.new expect(@lexi.eat_t("a")).to eq("a") end it "returns an empty string if the input is t" do @lexi =...
module DelayedCell class Queue def initialize(target) @target = target @jobs = [] @worker = Worker.new target, self end def push(job) @jobs << job @worker.async.start end def pop @jobs.shift end end end
def disp_plans(plans) puts "旅行プランを選択して下さい。" plans.each.with_index(1) do |plan,i| puts "#{i}. #{plan[:place]}旅行(#{plan[:price]}円)" end end def choose_plan(plans) while true print "プランの番号を選択 > " plan_num = gets.to_i break if (1..3).include?(plan_num) puts "1〜3の番号を入力して下さい。" end plans[plan_num -...
require 'spec_helper' class TestDocument < Document field :content, type: String, default: "" track_history on: :content, track_create: false end describe Document do # describe 'lock checking' do # it "starts out with a version of 1" do # doc = TestDocument.create # expect(doc.version).to eq 1 ...
require "spec_helper" describe UserImagesController do let(:user) { users(:no_picture) } before do log_in user any_instance_of(User) do |any_user| stub(any_user).save_attached_files { true } end end describe "#create" do context("for User") do let(:files) { [Rack::Test::UploadedFi...
require 'rails_helper' RSpec.describe "phrases/index", type: :view do before(:each) do assign(:phrases, [ Phrase.create!( :value => "MyText", :keyphrase => nil ), Phrase.create!( :value => "MyText", :keyphrase => nil ) ]) end it "renders a list of ...
class Tag < ApplicationRecord has_many :post_taggings has_many :posts, through: :post_taggings validates :name, presence: true validates :name, uniqueness: true end
class Raindrops def self.is_factor?(number, prime) (number % prime).zero? end def self.convert(number) output = ''.tap do |output| { 3 => 'Pling', 5 => 'Plang', 7 => 'Plong' }.each do |prime, sound| output << sound if is_factor?(number, prime) end end...
FactoryGirl.define do factory :suggestion do location_name 'Apple Inc.' latitude 37.331741 longitude(-122.030333) address '1 Infinite Loop' formatted_address "1 Infinite Loop\nCupertino, CA 95014" city 'Cupertino' state 'CA' experience_name 'Visit Apple Headquarters!' description '...
class UpdateContractsController < ApplicationController before_action :authenticate_consultant! def skip session[:skip_update_contract] = true redirect_to after_sign_in_path_for(current_consultant), notice: "Please remember to update your contract later." end def new @contract = Contract.for_consu...
module MongoDoc class InvalidEmbeddedHashKey < RuntimeError; end module Associations class HashProxy include ProxyBase HASH_METHODS = (Hash.instance_methods - Object.instance_methods).map { |n| n.to_s } MUST_DEFINE = %w[to_a inspect to_bson ==] DO_NOT_DEFINE = %w[merge! replace store...
class CreatePermissions < ActiveRecord::Migration[5.1] def change create_table :permissions do |t| t.string :kind, null: false, default: :user t.belongs_to :user, null: false t.string :permitted_actions, null: false end add_index :permissions, %i[kind user_id], unique: true end end
describe Spree::ShippingMatrixCalculator do let(:variant1) { build(:variant, price: 10) } let(:variant2) { build(:variant, price: 20) } let(:role) { create(:role) } let(:user) { create(:user, spree_roles: [role]) } let (:package) { build(:stock_package, variants_contents: { variant1 => 4, variant2 => 6 }) }...
class CreateClimbSessions < ActiveRecord::Migration[5.0] def change create_table :climb_sessions do |t| t.integer :host_id t.integer :guest_id t.integer :gym_id t.text :notes t.timestamps end end end
module ApplicationHelper def bootstrap_alert_class(type) case type when 'notice' 'success' when 'alert' 'danger' else type end end def page_title(title) content_for :title, title title end end
require 'spec_helper' require_relative 'pipeline_helper' describe RailsPipeline::IronmqPublisher do before do @default_emitter = DefaultIronmqEmitter.new({foo: "baz"}, without_protection: true) end it "should call post for IronMQ" do expect_any_instance_of(IronMQ::Queue).to receive(:post) { |instance, s...
# Дополнительное поле в тикете class TicketField < ActiveRecord::Base has_paper_trail default_scope order("#{table_name}.name asc") has_many :ticket_field_relations has_many :ticket_questions, through: :ticket_field_relations attr_accessible :name, :required, :hint, as: :admin validates :name, p...
class UsersController < ApplicationController before_filter :action_path def action_path; @action = params[:action].dup.prepend("can_").concat("?").to_sym end def authorized?(resource) error_redirect unless resource.send(@action,current_member,@team.id) end before_filter :read_path def read_path @team = ...
class CounselorSupervisor < ActiveRecord::Base attr_accessible :employee_id, :employee_department_id, :employee_position_id belongs_to :employee belongs_to :employee_department has_many :batch_counselor_supervisors def to_label employee.to_label end end
class BlocksController < ApplicationController before_filter :authenticate_user! before_filter :is_admin? # GET /blocks # GET /blocks.json def index @blocks = Block.order(:block_name).all respond_to do |format| format.html # index.html.erb format.json { render :json => @blocks } end...
require 'spec_helper' require 'deepstruct' require 'pebblebed/config' require 'pebblebed/connector' require 'pebblebed/security/role_schema' describe Pebblebed::Security::RoleSchema do class InvalidRoleSchema < Pebblebed::Security::RoleSchema role :guest, :capabilities => [], :requirements => [] role :cont...
# Cookbook Name:: kafka_console # Recipe:: pkg_install.rb # # Copyright 2015, @WalmartLabs # # All rights reserved - Do Not Redistribute # install kafka binary payLoad = node.workorder.payLoad[:kafka].select { |cm| cm['ciClassName'].split('.').last == 'Kafka'}.first Chef::Log.info("payload: #{payLoad.inspect.gsub("\n...
class CreatePhotos < ActiveRecord::Migration def up create_table :photos do |t| t.string :path t.string :token t.integer :file_size t.integer :boost, default: 0 t.timestamps end add_index :photos, :token end def down drop_table :photos end end
class Freezer < ApplicationRecord has_many :items has_and_belongs_to_many :users, {:join_table => :user_freezers} validates :name, presence: true accepts_nested_attributes_for :items def number_of_items self.items.count end def items_attributes=(items_attributes) attr = items_attributes["0"] ...
describe Pantograph do describe Pantograph::PantFile do describe "Opt Out Usage" do it "works as expected" do Pantograph::PantFile.new.parse("lane :test do opt_out_usage end").runner.execute(:test) expect(ENV['PANTOGRAPH_OPT_OUT_USAGE']).to eq("YES") end end end...
# frozen_string_literal: true require 'rails_helper' RSpec.describe Readings::Find do subject { described_class.run(params) } let(:params) do { number: number, household_token: thermostat.household_token } end before do allow(Rails.configuration.redis).to receive(:get).with("#{thermo...
class LikesController < ApplicationController # GET /likes # GET /likes.json def index @likes = Like.all respond_to do |format| format.html # index.html.erb format.json { render json: @likes } end end # GET /likes/1 # GET /likes/1.json # GET /likes/new # GET /likes/new.json ...
# frozen_string_literal: true module Diplomat class KeyNotFound < StandardError; end class PathNotFound < StandardError; end class KeyAlreadyExists < StandardError; end class AclNotFound < PathNotFound; end class AclAlreadyExists < StandardError; end class EventNotFound < StandardError; end class EventAl...
require 'pry' class String def sentence? self[-1] == '.' end def question? self[-1] == '?' end def exclamation? self[-1] == '!' end def count_sentences punctuation = ['.', '?', '!'] split_string = split(Regexp.union(punctuation)) split_string.delete('') split_string.length ...
class Bishop < Piece attr_reader :color, :type, :position include SlidingPiece def initialize(board=nil, position = nil, color) @board = board @position = position @color = color @type = :bi @direction = [[1,1],[-1,1],[-1,-1],[1,-1]] end def move_dirs @direction.dup end end
#this file demonstration of function declaration in ruby #this is function defintion #start of multiline comment =begin this is a multiline comment structure of a function is def keyword followed by function_name body of function end- denotes the end of function body =end #end of multiline comment def func(par...
namespace :test do desc 'run functional tests' task :functional do ruby './test/functional/suite.rb' ruby './test/functional/for_redcloth.rb' unless (''.chop! rescue true) end desc 'run unit tests' task :units do ruby './test/unit/suite.rb' end scanner_suite = 'test/scanners/suite.rb' ...
# frozen_string_literal: true class Article < ApplicationRecord has_many :comments, dependent: :destroy belongs_to :user validates :title, presence: true, length: { minimum: 5 } validates :text, presence: true, length: { maximum: 141 } end
require 'spec_helper' describe PaypalDetailsController do after(:all) do PaypalDetail.delete_all User.delete_all end before(:each) do @request.env["devise.mapping"] = Devise.mappings[:user] @user = FactoryGirl.create(:user) FactoryGirl.create(:configuration_setting) @user.confirm! # set a...
module Api module V1 class Api::V1::FlightsController < Api::V1::ApplicationController def index @flights = Flight.includes(:rocket).order(launched_at: :desc).all @flights = @flights.filter_reddit_links if params[:with_reddit] == "1" @flights = @flights.filter_successful_launches if...
require 'lib/fraccionarios' require 'test/unit' class TestFraccionario < Test::Unit::TestCase def setup @numero_fraccionario_1 = Numero_Fraccionario.new(10,5) @numero_fraccionario_2 = Numero_Fraccionario.new(20,10) end def test_tos assert_equal("10/5", @numero_fraccionario_1.to_s) assert_equal("20/10...
# compares RSS feeds RSpec::Matchers.define :have_data_from do |internal_feed| match do |actual_feed| @errors = [] if actual_feed.channel.title !~ /#{internal_feed.username}/ @errors << "Feed title mismatch: expected: '#{actual_feed.channel.title}' to contain '#{internal_feed.username}'" end ...
class AddColumnfToProfessionals < ActiveRecord::Migration def change add_column :professionals, :cv, :string add_column :professionals, :cv_file_name, :string add_column :professionals, :cv_content_type, :string add_column :professionals, :cv_file_size, :integer add_column :professionals, :cv_upda...
class Outpost::HomeController < Outpost::BaseController def dashboard breadcrumb "Dashboard", outpost.root_path end end
module Catalog class TopologyError < StandardError; end class RBACError < StandardError; end class ApprovalError < StandardError; end class NotAuthorized < StandardError; end class InvalidNotificationClass < StandardError; end class InvalidParameter < StandardError; end end
require "test_helper" describe Order do let(:o1) { orders(:o1) } let(:oi1) { order_items(:oi1) } let(:oi2) { order_items(:oi2) } let(:p1) { products(:p1) } let(:p2) { products(:p2) } let (:empty_order) { Order.create() } describe "RELATIONSHIPS" do it "can have many order items" do ...
# == Schema Information # # Table name: course_phases # # id :integer not null, primary key # subject_id :integer # phase_id :integer # created_at :datetime not null # updated_at :datetime not null # require 'rails_helper' RSpec.describe CoursePhase, type: :model do context '...
# Paperclip allows file attachments that are stored in the filesystem. All graphical # transformations are done using the Graphics/ImageMagick command line utilities and # are stored in Tempfiles until the record is saved. Paperclip does not require a # separate model for storing the attachment's information, instead a...
require "formula" class Atk < Formula homepage "http://library.gnome.org/devel/atk/" url "http://ftp.gnome.org/pub/gnome/sources/atk/2.14/atk-2.14.0.tar.xz" sha256 "2875cc0b32bfb173c066c22a337f79793e0c99d2cc5e81c4dac0d5a523b8fbad" bottle do revision 1 sha1 "5a014bce43ff14675bec23b61909d3d85cff20f1" =>...
class LanguagesController < ApplicationController before_action :logged_in? before_action :current_user, only:[:create, :destroy] def new_or_destroy @language = Language.new end def create if language_params[:name].empty? && language_params[:id].nil? redirect_to new_or_delete_language_path ...
require 'devise' require 'rails' DEVISE_PATH = File.expand_path(File.join(File.dirname(__FILE__), '..', '..')) module Devise class Railtie < Rails::Railtie railtie_name :devise def load_paths Dir["#{DEVISE_PATH}/app/{mailers,controllers,helpers}"] end # TODO: 'after' and 'before' hooks a...
require 'rails_helper' describe 'pages/new' do before:each do assign(:page, Page.new( title: 'MyString' )) end it 'renders new page form' do render assert_select 'form[action=?][method=?]', pages_path, 'post' do assert_select 'input[name=?]', 'page[title]' assert_select 'texta...
class IndividualsController < ApplicationController before_action :authenticate_user! before_action :set_individual, only: [:show, :edit, :update, :destroy] def index # @individuals = Individual.all respond_to do |format| format.html format.json { render json: IndividualDatatable.new(params) ...
# -*- encoding: utf-8 -*- require 'eventbus/common_init' # This is taken almost directly from the Stomp gem's example # logger, with minor modifications. Will work on customizing later. # == Example STOMP call back logger class. # # Optional callback methods: # # * on_connecting: connection starting # * on_connect...
json.array!(@tokens) do |token| json.extract! token, :id, :status, :comment, :user_id json.url token_url(token, format: :json) end
name 'instana-agent' maintainer 'INSTANA Inc' maintainer_email 'stefan.staudenmeyer@instana.com' license 'Proprietary - All Rights Reserved' description 'Installs/Configures instana-agent' long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) version '0.1.0' provides 'instana-agent::default' provides...
class AddPickupAndDropoffToPassengers < ActiveRecord::Migration def self.up add_column :passengers, :pickup_at, :datetime add_column :passengers, :dropoff_at, :datetime end def self.down remove_column :passengers, :dropoff_at remove_column :passengers, :pickup_at end end
class AddRestaurantIdToSpecial < ActiveRecord::Migration def change add_column :specials, :restaurant_id, :integer end end
module RemoteStorage module BackendInterface class NotImplemented < Exception ; end def get_auth_token(user, password) $stderr.puts "WARNING: get_auth_token() always returns 'fake-token'" return 'fake-token' end def authorize_request(user, category, token) $stderr.puts "WARNING: ...
class Api::TagsController < ApplicationController before_action :require_logged_in before_action :proper_ownership, only: [:show, :update, :destroy] def index @tags = Tag.where(user_id: current_user.id) end def show @tag = Tag.find(params[:id]) end def create @tag = Tag.new(tag_params) ...
module API module Spotify WS_URL = "https://api.spotify.com/v1" PERMITTED_TYPES = %w{album artist track} URI_REGEX = /spotify:([a-z]+):(\w+)/ def search(query) # Check that parameters are correct or return the corresponding error query = query.gsub('!ssearch', '').strip type, q = qu...
cars = 100 #Assigns the variable "cars" with the number 100 space_in_a_car = 4.0 #Assigns the variable "space_in_a_car" the number 4.0 drivers = 30 #Assigns the variable "drivers" the number 30 passengers = 90 #Assigns the variable "passengers" the number 90 cars_not_driven = cars - drivers #Assigns the variable "cars...
class AddApplicationToAppStatus < ActiveRecord::Migration def change add_reference :app_statuses, :student_application, index: true add_foreign_key :app_statuses, :student_applications end end
require 'osc' module Cosy # TODO: rather than use this artificially imposed class hierarchy # it would be cleaner to use the "Chain of Responsibility" pattern # and make this one handler that can be chained up to handel events class AbstractOscRenderer < AbstractRenderer def initialize(options={}) ...
module V1 class AuthAPI < Base resource :auth do desc "Creates and returns access_token if valid signin" params do requires :email, type: String, desc: "Email address" requires :password, type: String, desc: "Password" end post :signin do user = User.where(email: params[:email]).first ...
class User < ActiveRecord::Base # :token_authenticatable, :confirmable, # :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable devise :omniauthable # Setup accessible (or protected) attributes for your model ...
class QuotaPlan < Plan attr_accessible :quota # Hack to calculate the optimal price. We will retire quota plan soon def self.price quota plan100 = quota / 50 plan50 = (quota % 50) / 20 plan100 * 100 + plan50 * 50 end def self.customize price, quota, name="" name = "#{quota} credits plan" if ...
class Api::V2::MatchesController < ApplicationController before_action :load_table before_action :authorize_ongoing_match, only: :setup after_action :update_match_channel, except: :show def ongoing match = @table.ongoing_match authorize! :read, match render_match(match) end # FIXME: This actio...
require 'sinatra' require 'dotenv/load' require 'airrecord' require 'pry' require 'haml' set :protection, :except => :frame_options set :bind, '0.0.0.0' # When browser requests default page for domain, the path is '/' # The most basic thing to do is return a string of HTML that the browser will display get '/' do "...