text
stringlengths
10
2.61M
class Client < ActiveRecord::Base has_one :address has_many :orders has_and_belongs_to_many :roles scope :week, where("created_at > ?", DateTime.now-7.days).limit(5) scope :last_week, lambda { where("created_at < ?", Time.zone.now ) } scope :one_week_before, lambda { |time| where("created_at < ?", time) } end
require 'rbbt/rest/common/misc' module RbbtRESTHelpers def input_label(id, name, description = nil, default = nil, options = {}) options ||= {} text = consume_parameter :label, options if text.nil? text = name.to_s text += html_tag('span', " (default: " << default.to_s << ")", :class => 'input_default') unless default.nil? end label_id = id.nil? ? nil : 'label_for__' << id html_tag('label', text, {:id => label_id, :for => id, :title => description}.merge(options)) end def file_or_text_area(id, name, value, tsv = false) text_area_string = tsv ? "or use the text area below (you may use ',' intead of tabs)" : "or use the text area below" html_tag("input", nil, :type => "file", :id => (id.nil? ? nil : id + "__" + "param_file"), :name => name.to_s + "__" + "param_file") + html_tag("span", text_area_string, :class => "file_or_text_area") + html_tag("textarea", value || "" , :name => name, :id => id ) end def tar_file(id, name, value) tar_msg = "File in tar.gz format with directory as only first level entry" html_tag("input", nil, :type => "file", :id => (id.nil? ? nil : id + "__" + "param_file"), :name => name.to_s + "__" + "param_file") + html_tag("span", tar_msg, :class => "file_or_text_area") end def form_input(name, type, default = nil, current = nil, description = nil, id = nil, extra = {}) html_options = consume_parameter(:html_options, extra) || {} no_file = extra[:no_file] if extra case type when :multiple choices = consume_parameter(:choices, extra) default = default.collect{|o| o.to_s} if default current = current.collect{|o| o.to_s} if current input_label(id, name, description, Array === default ? default * ", " : nil, extra) + choices.collect do |choice| choice_name = name.to_s + "[#{ choice }]" check_true = (current && current.include?(choice.to_s)) || (default && default.include?(choice.to_s)) check_true = false if check_true.nil? check_false = ! check_true choice_id = id + "[#{ Misc.snake_case(choice) }]" if id false_id = choice_id + '_false' true_id = choice_id + '_true' else false_id = nil true_id = nil end choice_html = html_tag("input", nil, :type => :checkbox, :checked => check_true, :name => choice_name, :value => "true", :id => choice_id) + input_label(choice_id, choice, choice, nil, extra.merge({:class => :inline})) html_tag('span', choice_html, :class => 'choice') end * "\n" when :boolean current = param2boolean(current) unless current.nil? default = param2boolean(default) unless default.nil? check_true = current.nil? ? default : current check_true = false if check_true.nil? check_false = ! check_true if id false_id = id + '__' << 'false' true_id = id + '__' << 'true' else false_id = nil true_id = nil end input_label(id, name, description, default, extra) + html_tag("input", nil, :type => :checkbox, :checked => check_true, :name => name, :value => "true", :id => id) + html_tag("input", nil, :type => :hidden, :name => name.to_s + "_checkbox_false", :value => "false") when :string, :float, :integer, :hidden value = current.nil? ? default : current input_type = case type when :string "text" when :hidden "hidden" else "number" end step = case type when :string nil when :float "any" when :integer 1 end if input_type == 'hidden' html_tag("input", nil, html_options.merge(:type => input_type, :name => name, :value => value, :id => id, :step => step)) else input_label(id, name, description, default, extra) + html_tag("input", nil, html_options.merge(:type => input_type, :name => name, :value => value, :id => id, :step => step)) end when :tsv, :array, :text, :file value = current.nil? ? default : current value = value * "\n" if Array === value if no_file input_label(id, name, description, nil, extra) + html_tag("textarea", value || "" , :name => name, :id => id ) else input_label(id, name, description, nil, extra) + file_or_text_area(id, name, value, type == :tsv) end when :select value = current.nil? ? default : current allow_empty = consume_parameter :allow_empty, extra select_options = consume_parameter :select_options, extra if select_options options = select_options.collect do |option| option, option_name = option if Array === option option_name = option if option_name.nil? html_tag('option', option_name, :value => option, :selected => option.to_s == value.to_s) end else options = [] end options.unshift html_tag('option', 'none', :value => 'none', :selected => value.to_s == 'none') if allow_empty input_label(id, name, description, default, extra) + html_tag('select', options * "\n", html_options.merge(:name => name, :id => id, "attr-selected" => (value ? value.to_s : ""))) when :directory value = current.nil? ? default : current input_label(id, name, description, nil, extra) + tar_file(id, name, value) else "<span> Unsupported input '#{name}' type: #{type} </span>" end end end
class RemoveReportUrlFragmentFromProjects < ActiveRecord::Migration def change remove_column :projects, :ci_report_url_fragment end end
# ConcernedWithRailsDevBoost module RailsDevBoostConcernedWithFix def concerned_with_with_dependency_tracking(*args) concerned_with_without_dependency_tracking(*args) my_file_path_without_rb = ActiveSupport::Dependencies.search_for_file(name.underscore).sub(/\.rb\Z/, '') args.each do |dependency| # Handle the case, when the parent object is changed, i.e. - make sure require_dependency does go through next time dep_file_path = ActiveSupport::Dependencies.search_for_file("#{name.underscore}/#{dependency}") dep_file_path_withour_rb = dep_file_path.sub(/\.rb\Z/, '') ActiveSupport::Dependencies.loaded.delete(dep_file_path_withour_rb) # Handle the case, when concerned_with file changes by associating a dummy constant with it and setting up changed status propagation dummy_const_name = "ConcernedWith__#{name.underscore}_#{dependency}" const_set(dummy_const_name, Module.new) dummy_const_full_name = "#{name}::#{dummy_const_name}" # track the concerned_with file ActiveSupport::Dependencies.associate_constants_to_file([dummy_const_full_name], dep_file_path) # set the unload parent trigger ActiveSupport::Dependencies.file_map[dep_file_path_withour_rb].concerned_with_parent = my_file_path_without_rb end end def self.included(base) base.alias_method_chain :concerned_with, :dependency_tracking end end
class Properties def initialize(filename) @filename = filename end def property(mailaddr) File.open(@filename, 'r') do |f| f.read.split("\n").each do |line| break line.split('=')[1] if line.match(/#{mailaddr}/) end end end end
require 'json' require 'bunny' require 'pebblebed/river/subscription' module Pebblebed class River class << self attr_accessor :rabbitmq_options def route(options) raise ArgumentError.new(':event is required') unless options[:event] raise ArgumentError.new(':uid is required') unless options[:uid] uid = Pebblebed::Uid.new(options[:uid]) key = [options[:event], uid.klass, uid.path].compact key.join('._.') end end def initialize(env = ENV['RACK_ENV']) @environment = env || 'development' end def connected? bunny.connected? end def connect unless connected? bunny.start end end def disconnect bunny.stop if connected? end def publish(options = {}) connect persistent = options.fetch(:persistent) { true } key = self.class.route(options) exchange.publish(options.to_json, :persistent => persistent, :key => key) end def queue(options = {}) connect raise ArgumentError.new 'Queue must be named' unless options[:name] queue = channel.queue(options[:name], :durable => true) Subscription.new(options).queries.each do |key| queue.bind(exchange.name, :key => key) end queue end def exchange_name unless @exchange_name name = 'pebblebed.river' name << ".#{environment}" unless production? @exchange_name = name end @exchange_name end private def environment @environment end def bunny @bunny ||= Bunny.new(::Pebblebed::River.rabbitmq_options || {}) end def production? environment == 'production' end def channel connect @channel ||= @bunny.create_channel end def exchange connect @exchange ||= channel.exchange(exchange_name, :type => :topic, :durable => :true) end end end
class Review < ApplicationRecord enum review_type: %i(training testing).freeze end
class PiedPiper::Cli attr_accessor :name def initialize(name) @name = name end def call puts "loading..." puts "" puts "Welcome to Pied Piper!" PiedPiper::Scraper.new("http://www.piedpiper.com/#team").scrape puts "#{self.name}" start end def start puts "" puts "Type SV to meet some pipers or" puts "" puts "Type EXIT to leave program" puts "" input = gets.strip if input.upcase == "SV" list_pipers elsif input.upcase == "EXIT" puts "See ya! Happy Programming ✌️" else invalid start end end def list_pipers puts "" PiedPiper::Piper.all.each_with_index do |piper,index| puts "#{index + 1}.#{piper.name}" end puts "" puts "Which piper would you like to know more about? Enter a number 1-6 or type EXIT to leave 🙃" input = gets.strip if input.to_i > 0 && input.to_i <= PiedPiper::Piper.all.length print_info(input) piper_info elsif input.upcase == "EXIT" puts "Live Long and Prosper 🖖" else invalid list_pipers end end def piper_info puts "Would you like to meet another piper? Enter a Y or type EXIT to leave 🙃" input = gets.strip if input.upcase == "Y" list_pipers elsif input.upcase == "EXIT" puts "" puts "See ya! Happy Programming ✌️" else invalid end end def print_info(input) piper = PiedPiper::Piper.all[input.to_i - 1] puts "" puts "---------- #{piper.name} ----------" puts "" puts "---------- #{piper.postion} ----------" puts "" puts "" puts "Click link to view photo of #{piper.name}: #{piper.photo}" puts "" end def invalid puts "" puts "Incorrect Input. Please try again." puts "" end end
# frozen_string_literal: true class User < ActiveRecord::Base # ===== Decription: # Required for authentication user devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable include DeviseTokenAuth::Concerns::User # ===== Decription: # Relations between models has_many :concerts, dependent: :destroy has_many :comments, dependent: :destroy end
class SurfResortReviewsController < ApplicationController before_action :logged_in_user, only: [:new, :create, :edit, :update, :destroy] before_action :find_surf_resort, only: [:new, :create, :edit, :update, :destroy] before_action :find_surf_resort_review, only: [:edit, :update, :destroy] before_action :correct_user, only: [:edit, :update, :destroy] def new @surf_resort_review = SurfResortReview.new end def create @surf_resort_review = SurfResortReview.new(surf_resort_review_params) @surf_resort_review.surf_resort_id = @surf_resort.id @surf_resort_review.user_id = current_user.id if @surf_resort_review.save flash[:success] = "Your review has been added." redirect_to @surf_resort else render 'new' end end def edit end def update if @surf_resort_review.update(surf_resort_review_params) flash[:success] = "Your review has been updated." redirect_to @surf_resort else render 'edit' end end def destroy @surf_resort_review.destroy flash[:success] = "Your review has been removed." redirect_to @surf_resort end private def surf_resort_review_params params.require(:surf_resort_review).permit(:rating, :title, :comment) end # Before filters. # Find surf resort. def find_surf_resort @surf_resort = SurfResort.friendly.find(params[:surf_resort_id]) end # Find surf resort review. def find_surf_resort_review @surf_resort_review = SurfResortReview.friendly.find(params[:id]) end # Confirms the correct user. def correct_user redirect_to(@surf_resort) unless current_user?(@surf_resort_review.user) end end
############################################################################### # Datatype to represent an item belonging to a season. A collection of # EpisodeItems. ############################################################################### class Episode < ActiveRecord::Base include SoftDelete belongs_to :season has_many :episode_items, inverse_of: :episode, dependent: :destroy scope :published, ->{ where({deleted_at: nil}) } scope :deleted, ->{ where.not(deleted_at: nil) } validates :season_id, presence: true, numericality: { only_integer: true } validates :description, format: { without: DontGoToWork::EMPTY_SPACE_PATTERN } validates :order, presence: true, numericality: { only_integer: true, greater_than: -1 } validates :title, presence: true, uniqueness: true, length: { in: 3..64 }, format: { with: DontGoToWork::TITLE_PATTERN } validates :short_description, presence: true, length: {in: 3..256}, format: { without: DontGoToWork::EMPTY_SPACE_PATTERN } end
class UserModel attr_accessor :id, :name, :email, :password def to_hash { name: @name, email: @email, password: @password, } end end
require 'test_helper' class RecipesTest < ActionDispatch::IntegrationTest def setup @chef = Chef.create!(chefname: "mashrur", email: "vincent@example.com", password: "password", password_confirmation: "password") @recipe = Recipe.create(name: "Vegetable sauce", description: "great vegetable sautee, add vegetable and oil", chef: @chef) @recipe2 = @chef.recipes.build(name: "Chicken saute", description: "great chicken dish") @recipe2.save end test "Should get recipes index" do # Tests for Index page, Routes and Controller action get recipes_url assert_response :success end test "should get recipes listing" do get recipes_path assert_template 'recipes/index' #assert_match @recipe.name, response.body - No longer valid as we are testing for links as well!! assert_select "a[href=?]", recipe_path(@recipe), text: @recipe.name #assert_match @recipe2.name, response.body assert_select "a[href=?]", recipe_path(@recipe2), text: @recipe2.name end test "Should get to recipes show" do # tests for the show page, Routes and controller action sign_in_as(@chef, "password") #from test_helper get recipe_path(@recipe) assert_template 'recipes/show' assert_match @recipe.name, response.body assert_match @recipe.description, response.body assert_match @chef.chefname, response.body assert_select "a[href=?]", edit_recipe_path(@recipe), text: "Edit This Recipe" assert_select "a[href=?]", recipe_path(@recipe), method: :delete, text: "Delete This Recipe" assert_select "a[href=?]", recipes_path, text: "All Recipes" end test "Create a new valid recipe" do # 34, 47 test for New recipe sign_in_as(@chef, "password") #from test helper get new_recipe_path #This will show an error once login and session controllers are created - refer to app/test/test_helper.rb @sign_in_as assert_template "recipes/new" name_of_recipe = "Chicken saute" description_of_recipe = "great chicken dish" assert_difference "Recipe.count", 1 do post recipes_path, params: { recipe: { name: name_of_recipe, description: description_of_recipe}} end follow_redirect! assert_match name_of_recipe.capitalize, response.body assert_match description_of_recipe, response.body end test "Reject invalid recipe submissions" do sign_in_as(@chef, "password") get new_recipe_path assert_template "recipes/new" assert_no_difference "Recipe.count" do post recipes_path, params: { recipe: { name: " ", description: " "}} end assert_template "recipes/new" assert_select "h2.panel-title" assert_select "div.panel-body" end end
class Concert < ActiveRecord::Base has_many :reviews has_many :users, through: :reviews validates :name, presence: true validates :artist, presence: true validates :venue, presence: true # binding.pry def self.venue_order @concert = Concert.order('venue ASC') end end
module Actions class ChangeApiTier extend Extensions::Parameterizable with :api, :tier def call ActiveRecord::Base.transaction do api.tier_usage.deactivate! Models::TierUsage.create! api: api, tier: tier end end end end
class LocalityError < StandardError; end class Locality include Geokit::Mappable def self.resolve(s) begin geoloc = geocode(s) case geoloc.provider when 'google', 'yahoo' case geoloc.precision when 'country' # find database object object = Country.find_by_code(geoloc.country_code) when 'state' # map state codes map_state_codes(geoloc) # find database object, geoloc state is the state code, e.g. "IL" object = State.find_by_code(geoloc.state) when 'city' # map state codes map_state_codes(geoloc) # find state database object state = State.find_by_code(geoloc.state) # find city from state object = state.cities.find_by_name(geoloc.city) when 'zip' # map state codes map_state_codes(geoloc) # find state database object state = State.find_by_code(geoloc.state) if geoloc.provider == 'yahoo' # yahoo returns a zip precision for cities and zips if geoloc.zip.blank? # its a city - find city from state object = state.cities.find_by_name(geoloc.city) else # its a zip - find zip from state object = state.zips.find_by_name(geoloc.zip) end else # google zip really means a zip - find zip from state object = state.zips.find_by_name(geoloc.zip) end end return object end rescue return nil end return nil end # check the specified city/zip in the specified state # throws a LocalityError exception if the city/zip does not exist in the specified state def self.check(state, type, name) raise ArgumentError, "state required" if state.blank? or !state.is_a?(State) case type.to_s.titleize when 'City' s = "#{name} #{state.name}" geoloc = geocode(s) when 'Zip' s = "#{state.name} #{name}" geoloc = geocode(s) else raise ArgumentError, "invalid type #{type}, #{name}" end # find class object we are trying to find or create klass = Kernel.const_get(type.to_s.titleize) if geoloc.provider == 'google' # the google geocoder if geoloc.precision == type.to_s.downcase # find or create city or zip # use the geoloc name as the 'official' name, unless its blank, which allows mis-spellings to be normalized by the geocoder name = geoloc.send(type.to_s.downcase).blank? ? name : geoloc.send(type.to_s.downcase) object = klass.find_by_name_and_state_id(name, state.id) || klass.create(:name => name, :state => state, :lat => geoloc.lat, :lng => geoloc.lng) else raise LocalityError, "invalid #{type}, #{name}" end elsif geoloc.provider == 'yahoo' # the yahoo geocoder case type.to_s.downcase when 'city' # yahoo precision field is 'city' or 'zip', city must be valid, state code must match if (geoloc.precision == type.to_s.downcase or geoloc.precision == 'zip') and !geoloc.send(type.to_s.downcase).blank? and geoloc.state == state.code # use the geoloc name as the 'official' name name = geoloc.send(type.to_s.downcase) object = klass.find_by_name_and_state_id(name, state.id) || klass.create(:name => name, :state => state, :lat => geoloc.lat, :lng => geoloc.lng) end when 'zip' # yahoo precision field is 'zip', zip must be valid, state code must match if geoloc.precision == type.to_s.downcase and !geoloc.send(type.to_s.downcase).blank? and geoloc.state == state.code name = geoloc.send(type.to_s.downcase) object = klass.find_by_name_and_state_id(name, state.id) || klass.create(:name => name, :state => state, :lat => geoloc.lat, :lng => geoloc.lng) end else raise LocalityError, "invalid #{type}, #{name}" end end return object end # find the specified locality in the database, and return nil if its not there # - "Chicago, IL" should map to the city object 'Chicago' def self.search(s, options={}) # parse options log = options[:log] ? options[:log] : false match = s.match(/([A-Za-z ]+),{0,1} ([A-Z][A-Z])/) if match city_name = match[1] state_code = match[2] # search database for city and state state = State.find_by_code(state_code) return nil if state.blank? city = state.cities.find_by_name(city_name) if log if city RAILS_DEFAULT_LOGGER.debug("*** mapped #{s} to #{city.name}") else RAILS_DEFAULT_LOGGER.debug("xxx could not map #{s} to a city") end end city else nil end end # set events count using sphinx facets for the specified locality klass def self.set_event_counts(klass) case klass.to_s.downcase when 'city' facet_string = :city_id when 'zip' facet_string = :zip_id when 'neighborhood' facet_string = :neighborhood_ids else raise ArgumentError, "invalid klass #{klass}" end geo_event_hash = Appointment.facets(:facets => facet_string)[facet_string.to_sym] geo_event_hash.each_pair do |klass_id, events_count| next unless object = klass.find_by_id(klass_id) object.events_count = events_count object.save end # return the number of objects updated geo_event_hash.keys.size end protected # map special state codes def self.map_state_codes(geoloc) return geoloc if geoloc.blank? or geoloc.state.blank? case geoloc.state.titleize when "N Carolina" geoloc.state = "NC" when "S Carolina" geoloc.state = "SC" when "S Dakota" geoloc.state = "SD" when "N Dakota" geoloc.state = "ND" when "Rhode Isl" geoloc.state = "RI" when "W Virginia" geoloc.state = "WV" end geoloc end end
require 'test_helper' class Admin::HomeControllerTest < ActionDispatch::IntegrationTest fixtures :seasons, :heroes test '404s for non-admin' do user = create(:user) account = create(:account, user: user) sign_in_as(account) get '/admin' assert_response :not_found end test '404s for anonymous user' do get '/admin' assert_response :not_found end test 'loads successfully for admin' do admin_account = create(:account, admin: true) match1 = create(:match, season: 1, heroes: [heroes(:mercy)]) user = create(:user) account = create(:account, user: user) friend = create(:friend, user: user) match2 = create(:match, result: :win, season: 2, account: account, group_member_ids: [friend.id], heroes: [heroes(:ana)]) placement_match = create(:match, placement: true, season: 1) placement_log_match = create(:match, placement: false, season: 1, map: nil, prior_match: nil, rank: 3000) sign_in_as(admin_account) get '/admin' assert_response :ok assert_select 'button', text: /#{admin_account.name}/ assert_select '.test-latest-matches span', text: 'Placement log' assert_select '.test-latest-matches span', text: 'Placement' assert_select '.test-latest-matches span', text: 'Win' assert_select '.test-latest-matches span', text: '1 hero' end end
class CreateEvents < ActiveRecord::Migration def change create_table :events do |t| t.string 'app_sha', null: false t.string 'ip', null: false end end end
require "spec_helper" RSpec.describe HerokuCLI::PG do let(:subject) { HerokuCLI::PG.new('test') } before do allow(subject).to receive(:heroku) { nil } end context 'info' do context 'only main' do before do allow(subject).to receive(:heroku) { file_fixture('pg_info') } end it 'will parse multiple databases' do expect(subject.info).to be_a(Array) expect(subject.info.size).to eq 1 end it { expect(subject.main.name).to eq 'DATABASE' } it { expect(subject.forks.map(&:name)).to eq [] } end context 'follower' do before do allow(subject).to receive(:heroku) { file_fixture('pg_info_follow') } end it 'will parse multiple databases' do expect(subject.info).to be_a(Array) expect(subject.info.size).to eq 2 end it { expect(subject.main.name).to eq 'DATABASE' } it { expect(subject.forks.map(&:name)).to eq [] } it { expect(subject.followers.map(&:name)).to eq ['HEROKU_POSTGRESQL_ORANGE'] } end context 'fork' do before do allow(subject).to receive(:heroku) { file_fixture('pg_info_fork') } end it 'will parse multiple databases' do expect(subject.info).to be_a(Array) expect(subject.info.size).to eq 2 end it { expect(subject.main.name).to eq 'DATABASE' } it { expect(subject.forks.map(&:name)).to eq ['HEROKU_POSTGRESQL_GRAY'] } it { expect(subject.followers.map(&:name)).to eq [] } end end context 'create_follower' do let(:db_info) { file_fixture('pg_info').split("\n") } let (:database) { HerokuCLI::PG::Database.new(db_info) } it 'with same plan' do expect(subject).to receive(:heroku).with("addons:create heroku-postgresql:standard-0 --follow postgresql-curved-12345") subject.create_follower(database) end it 'with the plan specified' do expect(subject).to receive(:heroku).with("addons:create heroku-postgresql:foobar --follow postgresql-curved-12345") subject.create_follower(database, plan: 'foobar') end end context 'un_follow' do before do allow(subject).to receive(:heroku).with('pg:info') { file_fixture('pg_info_follow') } end it 'fails if not follower' do database = subject.main expect { subject.un_follow(database) }.to raise_exception('Not a following database DATABASE') end it 'will unfollow' do database = subject.followers.first expect(subject).to receive(:heroku).with("pg:unfollow HEROKU_POSTGRESQL_ORANGE_URL -c test") subject.un_follow(database) end end context 'promote' do before do allow(subject).to receive(:heroku).with('pg:info') { file_fixture('pg_info_follow') } end it 'fails if already main' do database = subject.main expect { subject.promote(database) }.to raise_exception('Database already main DATABASE') end it 'will un_follow first' do database = subject.followers.first expect(subject).to receive(:un_follow).with(database, wait: false) { nil } expect(subject).to receive(:heroku).with('pg:promote postgresql-animated-12345') subject.promote(database, wait: false) end context 'ensure promoted master ready' do before do allow(subject).to receive(:heroku).with('pg:info') { file_fixture('pg_info_promote') } end it 'fails if already main' do database = subject.main expect(subject.main.follower?).to eq true end end end context 'reload' do it 'pick up changes in info' do allow(subject).to receive(:heroku).with('pg:info') { file_fixture('pg_info_follow') } expect(subject.main.name).to eq 'DATABASE' expect(subject.forks.map(&:name)).to eq [] expect(subject.followers.map(&:name)).to eq ['HEROKU_POSTGRESQL_ORANGE'] allow(subject).to receive(:heroku).with('pg:info') { file_fixture('pg_info_fork') } subject.reload expect(subject.main.name).to eq 'DATABASE' expect(subject.forks.map(&:name)).to eq ['HEROKU_POSTGRESQL_GRAY'] expect(subject.followers.map(&:name)).to eq [] end end context 'destroy' do before do allow(subject).to receive(:heroku).with('pg:info') { file_fixture('pg_info_fork') } end it 'fails if main' do database = subject.main expect { subject.destroy(database) }.to raise_exception('Cannot destroy test main database') end it 'will destroy addon' do database = subject.forks.first expect(subject).to receive(:heroku).with('addons:destroy HEROKU_POSTGRESQL_GRAY_URL -c test') subject.destroy(database) end end end
require 'helper' require 'media/filter/graph' module Media class Filter class TestGraph < MiniTest::Unit::TestCase def test_to_s assert_equal('a; b; c', Graph.new(chains: %w(a b c)).to_s) end end end end
class RemoveSellerIdFromProfile < ActiveRecord::Migration[5.2] def change remove_column :profiles, :seller_id, :integer end end
class Rating < ApplicationRecord belongs_to :user_selection validates :note, presence: true end
# frozen_string_literal: true class RegistrationGroupsController < AuthenticatedController before_action :assign_event before_action :assign_group, except: %i[new create] def new @group = RegistrationGroup.new end def show @attendance_list = @group.attendances.active.order(created_at: :desc) @attendance_list_csv = AttendanceExportService.to_csv(@attendance_list) end def destroy return redirect_to event_registration_groups_path(@event) if @group.destroy redirect_to(event_registration_groups_path(@event), flash: { error: @group.errors.full_messages.join(',') }) end def create @group = RegistrationGroup.new(group_params.merge(event: @event, leader: current_user)) if @group.save redirect_to event_path(@event) else render :new end end def update return redirect_to @event if @group.update(group_params) render :edit end private def group_params params.require(:registration_group).permit(:name, :discount, :minimum_size, :amount, :automatic_approval, :paid_in_advance, :capacity) end def assign_group @group = @event.registration_groups.find(params[:id]) end end
require 'bunny' require 'json' module Playlister module MessageQueue class Base attr_reader :connection, :channel, :exchange attr_accessor :name def initialize(queue_name = nil) @connection = Bunny.new @connection.start @channel = @connection.create_channel if queue_name @name = queue_name end @exchange = @channel.default_exchange end def queue @channel.queue @name end def send(message) @exchange.publish message.to_json, :routing_key => @name end end class RecentlyAdded < Base attr_reader :name def initialize super('recently_added') end end class AllSongs < Base attr_reader :name def initialize super('all_songs') end end end end
# == Schema Information # # Table name: attribution_portfolios # # id :integer not null, primary key # name :string not null # human_name :string # account_number :string # created_at :datetime not null # updated_at :datetime not null # class Attribution::Portfolio < ActiveRecord::Base attr_accessor :returns attr_reader :total_performance has_many :days, :class_name => "Attribution::Day", :dependent => :destroy has_many :holdings, :through => :days, dependent: :destroy has_many :transactions, :through => :days, dependent: :destroy after_initialize :set_portfolio_returns def set_portfolio_returns @returns = Attribution::PortfolioReturns.new end def calculate @total_performance = @returns.total end def day( date ) days.where( :date => date ).first_or_create! end def clear_data_on( date ) days.where( :date => date ).destroy_all end def holdings_on( date ) day( date ).holdings end def transactions_on( date ) day( date ).holdings end end
class Dream < Sinatra::Base enable :sessions # for use flash register Sinatra::ConfigFile helpers Sinatra::Cookies register Sinatra::MultiRoute register Sinatra::Flash register Sinatra::ActiveRecordExtension set :public_folder, File.dirname(__FILE__) + '/assets' set :views, File.dirname(__FILE__) + '/views' set :show_exceptions, true # use config/*.yml for settings register Sinatra::ConfigFile config_file 'config/application.yml' set :environments, %w(production, development) configure :development do register Sinatra::Reloader %w(models helpers controllers routes).each do |dir| Dir[ File.expand_path("../#{dir}/*.rb", __FILE__) ].each{|file| also_reload file } end require "better_errors" use BetterErrors::Middleware BetterErrors.application_root = __dir__ end after do ActiveRecord::Base.clear_active_connections! end end
class Pdnsd < Formula homepage "http://members.home.nl/p.a.rombouts/pdnsd/" url "http://members.home.nl/p.a.rombouts/pdnsd/releases/pdnsd-1.2.9a-par.tar.gz" version "1.2.9a-par" sha256 "bb5835d0caa8c4b31679d6fd6a1a090b71bdf70950db3b1d0cea9cf9cb7e2a7b" bottle do cellar :any sha256 "a55b3ea9a71be9bee77ddb9ced37f77bc0f37376bf2d66ecdb7780282ae66e35" => :yosemite sha256 "4dc63c69195b38fdb977bfcedb97de860d21a61beb0e280634037c1dee8bd455" => :mavericks sha256 "473a9d25b7461badb8814355a313595c12240dd8054a6865acf709d85f197da2" => :mountain_lion end def install system "./configure", "--disable-debug", "--disable-dependency-tracking", "--prefix=#{prefix}", "--localstatedir=#{var}", "--sysconfdir=#{etc}", "--mandir=#{man}", "--with-cachedir=#{var}/cache/pdnsd" system "make", "install" end test do assert_match "version #{version}", shell_output("#{sbin}/pdnsd --version", 1) end end
class HomeController < ApplicationController before_action :authenticate_user!, only: [:management] before_action :is_admin?, only: [:management] def index @article = Article.all.order('created_at DESC').limit(5) set_page_title '首頁' end def aboutus set_page_title '關於我們' end def policy set_page_title '隱私權條款' end def shipping set_page_title '金物流政策' end def pay @payer = Payer.new end def create @payer = Payer.new(payer_params) if @payer.save render :new else render :new end end def management @customer = Customer.all @user = User.all @product=Product.all @article=Article.all @payer=Payer.all end def is_admin? redirect_to root_path unless current_user.admin? end private def payer_params params.require(:payer).permit(:payeraccount,:paymentprice) end def account_update_params params.require(:user).permit(:email, :password, :password_confirmation, :current_password, :admin, :username, :u_convenienceaddress, :u_homeaddress, :u_phone) end end
class TableAdmins < ActiveRecord::Migration def change create_table :admins add_column :admins, :name, :string add_column :admins, :password, :string end end
json.array!(@items) do |item| json.product do json.(item.product, :id, :name, :description, :price) json.images item.product.images do |image| json.(image, :thumbnail_url, :url) end end json.quantity item.quantity end
Rails.application.configure do config.cache_classes = false config.eager_load = false config.consider_all_requests_local = true config.action_controller.perform_caching = false config.action_mailer.raise_delivery_errors = false config.active_support.deprecation = :log config.active_record.migration_error = :page_load config.assets.debug = true config.assets.raise_runtime_errors = true config.i18n.default_locale = :en config.after_initialize do Bullet.enable = true Bullet.alert = true Bullet.bullet_logger = true Bullet.console = true end end
module Morpheus module ActsAsRestful extend ActiveSupport::Concern module InstanceMethods def id return nil unless rest url = rest["self"] return nil if url.blank? url.match(/(\d+)\/?$/)[1].to_i end def rest @rest ||= {} end def update_rest!(data) @rest = data.to_hash props = rest["data"] assign_attributes(props) if props && respond_to?(:assign_attributes) self end end end end
class Round include ActiveModel::Model ENUM_GROUP = { grupo_1: 1, grupo_2: 2, grupo_3: 3} attr_accessor :index, :player, :group, :play, :name, :group, :step def initialize(index, group, name) self.index = index.present? ? index.to_i : 1 self.group = group self.name = name end def next_index self.index + 1 end def step case self.round.to_i when 0..10 "FASE 1" when 10..50 "FASE 2" when 50..90 "FASE 3" end end def play!(choice) if self.index == 180 return false else return true end end def round self.index / 2 end def player if (self.index % 2) == 0 "Sua vez" elsif self.group != "1" "Vez do Computador" else "Sua vez" end end end
# frozen_string_literal: true class ProductRecipe < ApplicationRecord belongs_to :product has_many :ingredients, dependent: :destroy accepts_nested_attributes_for :ingredients, allow_destroy: true def credit_to_line(inventory_line, inv_map) max_quantity = find_max_quantity(inv_map) return unless max_quantity.positive? ingredients.each do |ingredient| inv_map[ingredient.product_id] -= max_quantity * ingredient.quantity end inventory_line.quantity_present += max_quantity inventory_line.save! end def debit_from_line(inventory_line, inv_map) max_quantity = [find_max_quantity(inv_map), inventory_line.quantity_present].min return unless max_quantity.positive? ingredients.each do |ingredient| inv_map[ingredient.product_id] -= max_quantity * ingredient.quantity end inventory_line.quantity_present -= max_quantity inventory_line.save! end def mutate_inv_map(inv_map) max_quantity = find_max_quantity(inv_map) return unless max_quantity.positive? ingredients.each do |ingredient| inv_map[ingredient.product_id] -= max_quantity * ingredient.quantity end inv_map[product_id] ||= 0 inv_map[product_id] += max_quantity end private def find_max_quantity(inv_map) ingredients.map { |i| max_ingredient(i, inv_map) }.min end def max_ingredient(ingredient, inv_map) max_quantity = 0 available = inv_map[ingredient.product_id].to_i max_quantity = (available - (available % ingredient.quantity)) / ingredient.quantity if available.positive? max_quantity end end
class CreateGoldenHorses < ActiveRecord::Migration[5.0] def change create_table :golden_horses do |t| t.integer :year t.integer :best_newcomer_id t.integer :best_supporting_actor_id t.integer :best_supporting_actress_id t.integer :best_actor_id t.integer :best_actress_id t.integer :best_screenplay_id t.integer :best_director_id t.timestamps end end end
require 'spec_helper' RSpec.describe Channel, type: :model do it { should validate_presence_of(:name) } it { should validate_uniqueness_of(:name) } describe 'associations' do it { should have_many(:messages) } it { should have_many(:subscriptions) } it { should have_many(:subscribers).through(:subscriptions) } it { should belong_to(:user) } end describe 'scopes' do specify('active') { expect(Channel.active.to_sql) .to eq "SELECT \"channels\".* FROM \"channels\" WHERE \"channels\".\"active\" = 't'" } specify('by_popularity') { expect(Channel.by_popularity.to_sql) .to eq "SELECT \"channels\".* FROM \"channels\" ORDER BY subscriptions_count desc" } end describe 'serialization, #to_h' do let(:channel) { create :channel, :full } specify do expect(channel.to_h).to eq( { id: channel.id, name: channel.name, image_url: "/uploads/channel/image/#{channel.id}/thumb_image.jpg", active: true }) end end end
require 'rails_helper' describe Api do describe 'GET /api/ping' do it "should return pong" do get '/api/ping' valid_response = { :pong => "ok" }.to_json expect(response.status).to eq 200 expect(response.body).to eq valid_response end end end
require "fastlane_core/ui/ui" module Fastlane UI = FastlaneCore::UI unless Fastlane.const_defined?("UI") module Helper class LocalizeHelper # class methods that you define here become available in your action # as `Helper::LocalizeHelper.your_method` # def self.getProjectPath(options) projectPath = nil unless options.nil? projectPath = options[:localize_project] end if projectPath.nil? projectPath = ENV["PROJECT_FILE_PATH"] end if projectPath.nil? projectPath = Dir.entries(".").select { |f| f.end_with?(".xcodeproj") }.first end if projectPath.nil? fail "no xcodeproject found" end projectPath end def self.getProject(options) project = Xcodeproj::Project.open(self.getProjectPath(options)) project end def self.getTargetName(options) project = self.getProject(options) targetName = nil unless options.nil? targetName = options[:localize_target] end if targetName.nil? targetName = ENV["TARGET_NAME"] end if targetName.nil? targetName = project.targets.map { |target| target.name.to_s }.first end if targetName.nil? fail "no target found" end targetName end def self.getTarget(options) project = self.getProject(options) targetName = self.getTargetName(options) target = project.targets.select { |target| target.name.eql? targetName }.first if target.nil? fail "no target" end target end def self.codeFiles(target, options) if options[:file_filter].nil? filter = [] else filter = (options[:file_filter]).split(",") end codeFiles = target.source_build_phase.files.to_a.map do |pbx_build_file| pbx_build_file.file_ref.real_path.to_s end.select do |path| path.end_with?(".swift") end.select do |path| bool = true filter.each { |filter| if path.include? filter bool = false end } next bool end.select do |path| File.exist?(path) end codeFiles end def self.stringsFromFile(file) strings = File.readlines(file).to_s.enum_for(:scan, /(?<!\#imageLiteral\(resourceName:|\#imageLiteral\(resourceName: |NSLocalizedString\()\\"[^\\"\r\n]*\\"/).flat_map { Regexp.last_match } return strings end def self.showStringOccurrencesFromFile(file, string) line_array = File.readlines(file) File.open(file).each_with_index { |line, index| if line =~ /(?<!\#imageLiteral\(resourceName:|\#imageLiteral\(resourceName: |NSLocalizedString\()#{Regexp.escape(string)}/ hits = line_array[index - 2..index - 1] + [line_array[index].green] + line_array[index + 1..index + 2] UI.message "In file #{file} (line #{index}): \n\n#{hits.join()}" end } end def self.whitelistFilename "fastlane/.fastlane_localization_whitelist" end def self.addToWhitelist(string) open(whitelistFilename, "a") { |f| f.puts string } UI.message "Added \"#{string}\" to #{whitelistFilename}" end def self.getWhitelist if File.exist?(whitelistFilename) return File.readlines(whitelistFilename).map(&:strip).map { |s| s.gsub(/^\\"/, "\"").gsub(/\\"$/, "\"") } else return [] end end def self.localize_string(string, key, files, params) open(params[:strings_file], "a") { |f| f.puts "\"#{key}\" = #{string};" } files.each do |file_name| text = File.read(file_name) new_contents = text.gsub(string, replacementString(key, params)) File.open(file_name, "w") { |file| file.puts new_contents } end UI.message "Replaced \"#{string}\" with \"#{replacementString(key, params)}\"" end def self.replacementString(key, params) if params[:use_swiftgen] swiftgenKey = key.gsub(".", "_").split("_").inject { |m, p| letters = p.split("") letters.first.upcase! p2 = letters.join m + p2 } return "L10n.#{swiftgenKey}" else return "NSLocalizedString(\"#{key}\")" end end end end end
class AddCollectionIdIndexToFileGroups < ActiveRecord::Migration def change add_index :file_groups, :collection_id end end
class P0200c attr_reader :options, :name, :field_type, :node def initialize @name = "Floor mat alarm (P0200c)" @field_type = RADIO @node = "P0200C" @options = [] @options << FieldOption.new("^", "NA") @options << FieldOption.new("0", "Not used") @options << FieldOption.new("1", "Used less than daily") @options << FieldOption.new("2", "Used daily") end def set_values_for_type(klass) return "0" end end
require File.expand_path('../spec_helper', __FILE__) Dir["./lib/*.rb"].each {|file| require File.expand_path('../../'+file, __FILE__)} describe BankingCodeChallenge::Bank do before :each do @bank1 = BankingCodeChallenge::Bank.new( "Bank1" ) @account_1_1 = BankingCodeChallenge::Account.new(1111,@bank1,1000) @account_1_2 = BankingCodeChallenge::Account.new(1122,@bank1,2000) @transfer1 = BankingCodeChallenge::Transfer.new(@account_1_1, @account_1_2, 500) @bank2 = BankingCodeChallenge::Bank.new( "Bank2" ) end describe 'validations' do context '.initialize' do it '#bank' do expect(@bank1).to be_an_instance_of(BankingCodeChallenge::Bank) end end context '.addAccount' do it 'successfully' do @bank1.addAccount(@account_1_2) expect(@bank1.accounts).to include(@account_1_2) end it 'with repeated number' do @bank1.addAccount(@account_1_2) expect{@bank1.addAccount(@account_1_2)}.to raise_error(RuntimeError) end end end end
# nginx ## dependencies include_recipe "../epel/default.rb" include_recipe "../ssl/default.rb" ## install package 'nginx' do action :install end ## service stop service 'nginx' do action [:stop] end remote_file "/etc/nginx/nginx.conf" do user "root" source :auto mode "644" owner "root" group "root" end template "/etc/nginx/conf.d/node.conf" do user "root" source :auto mode "644" owner "root" group "root" end remote_directory "/var/www/html" do source "files/var/www/html" mode "755" owner "root" group "root" end # execute "copy file" do # user "root" # command "cp -pr /usr/share/nginx/html/* #{node["nginx"]["doc_root"]}" # only_if "test -e /usr/share/nginx/html" # end ## service start service 'nginx' do action [:enable, :start] end # template "/etc/nginx/conf.d/site" do # source "nginx/site.erb" # notifies :reload, "service[nginx]" # end # service "nginx" do # action :restart # end # remote_file "/etc/nginx/conf.d/static.conf" # template "/etc/nginx/conf.d/dynamic.conf"
# encoding: utf-8 module Faceter module Functions # Ungroups array values using provided root key and selector # # @example # selector = Selector.new(only: :bar) # function = Functions[:ungroup, :qux, selector] # # function[[{ foo: :FOO, qux: [{ bar: :BAR }, { bar: :BAZ }] }]] # # => [{ foo: :FOO, bar: :BAR }, { foo: :FOO, bar: :BAZ }] # # @param [Array] array # @param [Object] key # @param [Selector::Condition] selector # # @return [Array<Hash>] # def self.ungroup(array, key, selector) array.flat_map do |hash| list = t(:to_tuples)[hash.delete(key)] group(list, key, !selector).map { |item| hash.merge(item) } end end end # module Functions end # module Faceter
json.array!(@pages) do |page| json.extract! page, :type_id, :title, :content, :status json.url page_url(page, format: :json) end
class Fregerepl < Formula desc "Formula for installing the Frege REPL (not the compiler!!!)" homepage "https://github.com/Frege/frege-repl" url "https://github.com/Frege/frege-repl/releases/download/1.4-SNAPSHOT/frege-repl-1.4-SNAPSHOT.zip" version "1.4-SNAPSHOT" sha256 "2cf1c2a8f7b64c9d70b21fbfd25b2af3f5e3bebe3662f724afd435d01bddafec" depends_on :java => "1.8+" def install # Before we even get here, Homebrew has already unpacked the zip file. # Get rid of Windows batch file since Homebrew only runs on OS X. rm_f Dir["bin/*.bat"] # Move both bin and lib directories under libexec to avoid putting jars # into /usr/local/lib (per Homebrew recommendations) while preserving # the need for the shell script to reference jar files in a parallel # directory and not having to tamper with the original shell script. libexec.install "bin", "lib" # Symlink to the real script. bin.install_symlink "#{libexec}/bin/frege-repl" end test do assert_match "65536", pipe_output("#{bin}/frege-repl", "println $ 64*1024\n:quit\n") end end
class AddDevteamFieldsToContact < ActiveRecord::Migration def change add_column :contact_requests, :test_suite, :boolean add_column :contact_requests, :ci_server, :boolean add_column :contact_requests, :deploy_master, :boolean add_column :contact_requests, :onestep_deploy, :boolean add_column :contact_requests, :bugs_not_issue, :boolean add_column :contact_requests, :releases_not_issue, :boolean add_column :contact_requests, :infrastructure_not_issue, :boolean add_column :contact_requests, :agile_product, :boolean add_column :contact_requests, :week_sprints, :boolean add_column :contact_requests, :weekly_retros, :boolean add_column :contact_requests, :analytics, :boolean end end
# frozen_string_literal: true Sequel.migration do change do create_table :stripe_invoices do primary_key :id foreign_key :user_id, SC::Billing.user_model.table_name, null: false, index: true foreign_key :subscription_id, :stripe_subscriptions, null: false, index: true String :stripe_id, null: false Jsonb :stripe_data, null: false Integer :total, null: false Integer :amount_due, null: false Integer :amount_paid, null: false String :currency, null: false DateTime :date, null: false DateTime :due_date FalseClass :forgiven, null: false FalseClass :closed, null: false FalseClass :attempted, null: false FalseClass :paid, null: false String :pdf_url DateTime :created_at, null: false, default: Sequel::CURRENT_TIMESTAMP DateTime :updated_at, null: false, default: Sequel::CURRENT_TIMESTAMP unique :stripe_id end end end
class CreateMetafields < ActiveRecord::Migration[5.0] def change create_table :metafields, id: :uuid do |t| t.string :description t.string :key t.string :namespace t.integer :owner_id t.integer :owner_type t.string :owner_resource t.string :value t.string :value_type t.timestamps end add_index :metafields, [:owner_type, :owner_id] end end
module DiscourseSimpleCalendar class CalendarDestroyer def self.destroy(post) fields = [ DiscourseSimpleCalendar::CALENDAR_CUSTOM_FIELD, DiscourseSimpleCalendar::CALENDAR_DETAILS_CUSTOM_FIELD ] PostCustomField.where(post_id: post.id, name: fields) .delete_all end end end
class UserInfo def initialize(user) @user = user end def created "You created your account on #{@user.created_at.strftime("%A %B %d, %Y")}." end def sign_ins "You have signed in #{@user.sign_in_count} times." end def simulations "You have ran #{@user.simulations_ran} simulations." end def progress if @user.has_setup_tracked_portfolio? "You completed a retirement simulation, and set up a tracked portfolio." elsif @user.has_completed_simulation? "You have completed a retirement simulation, but did not set up your portfolio." elsif @user.has_selected_portfolio? "You have selected a portfolio, but did not complete a retirement simulation." elsif @user.has_completed_questionnaire? "You have completed the risk tolerance questionnaire, but did not select a portfolio." else "You haven't completed the risk tolerance questionnaire yet." end end end
class EntityActionController attr_accessor :entity, :id attr_accessor :actions def initialize(entity, id = nil) @entity, @id = entity, id @actions = [] end def add(action, text = nil, resource = nil, params = {}) text = action if text.nil? resource = action.respond_to?(:resource) ? action.resource : nil resource ||= "Rbbt" @actions << [action, text, resource, params] end end module EntityRESTHelpers def default_action_controller(entity, list_id = nil) action_controller = EntityActionController.new(entity, list_id) case when Array === entity find_all_entity_list_action_templates(entity, true).each do |action| action_controller.add action, Misc.humanize(action, :format => :sentence), :reuse => true end when TSV === entity find_all_entity_map_action_templates(entity, true).each do |action| action_controller.add action, Misc.humanize(action, :format => :sentence), :reuse => true end else find_all_entity_action_templates(entity, true).each do |action| action_controller.add action, Misc.humanize(action, :format => :sentence) end end action_controller end def action_controller_render(controller) partial_render('entity_partials/action_controller', :controller => controller) end end
require_relative '../phase2/controller_base' require 'active_support' require 'active_support/core_ext' require 'erb' module Phase3 class ControllerBase < Phase2::ControllerBase # use ERB and binding to evaluate templates # pass the rendered html to render_content def render(template_name) raise StandardError if already_built_response? content = File.readlines(file_path(template_name)).join render_content(ERB.new(content).result(binding) ,"text/html") end def file_path(template_name) folder = self.class.name.underscore file_name = template_name.to_s + ".html.erb" file_path = "views/#{folder}/#{file_name}" end end end
# frozen_string_literal: true require 'rails_helper' RSpec.describe LandlordsController, type: :controller do let(:current_user) { create(:user) } let(:session) { { user_id: current_user.id } } let(:params) { {} } describe 'POST #create' do subject { post :create, params: params, session: session } context 'when valid landlord param attributes' do let(:valid_attributes) do { first_name: 'somelandlordfirstname', last_name: 'somelandlordlastname', email: 'somelandlordemail@topfloor.ie' } end let(:params) { { landlord: valid_attributes } } it 'assigns @landlord' do subject expect(assigns(:landlord)).to be_a Landlord end it 'creates a Landlord' do expect { subject }.to change(Landlord, :count).by(1) landlord = Landlord.last expect(landlord.first_name).to eq valid_attributes[:first_name] expect(landlord.last_name).to eq valid_attributes[:last_name] expect(landlord.email).to eq valid_attributes[:email] end it 'responds with 302 Found' do subject expect(response).to have_http_status(:found) end it 'redirects to landlords#show' do subject expect(response).to redirect_to Landlord.last end it 'assigns flash success' do subject expect(flash[:success]).to eq I18n.t(:success_create, scope: 'controllers.landlords.messages', first_name: valid_attributes[:first_name], last_name: valid_attributes[:last_name], email: valid_attributes[:email]) end end context 'when invalid landlord param attributes' do let(:invalid_attributes) { build(:landlord, first_name: '').attributes } let(:params) { { landlord: invalid_attributes } } it 'does not create a Landlord' do expect { subject }.to_not change(Landlord, :count) end it 'responds with unprocessable_entity' do subject expect(response).to have_http_status(:unprocessable_entity) end end context 'when user is not logged in' do subject { post :create, params: params, session: {} } it 'returns http forbidden status' do subject expect(response).to have_http_status(:forbidden) end it 'renders error page' do subject expect(response).to render_template('errors/not_authorized') end end end end
Metasploit::Model::Spec.shared_examples_for 'Module::Class' do # # Module::Ancestor factories # module_ancestor_factory = "#{factory_namespace}_module_ancestor" payload_module_ancestor_factory = "payload_#{module_ancestor_factory}" non_payload_module_ancestor_factory = "non_#{payload_module_ancestor_factory}" single_payload_module_ancestor_factory = "single_#{payload_module_ancestor_factory}" stage_payload_module_ancestor_factory = "stage_#{payload_module_ancestor_factory}" stager_payload_module_ancestor_factory = "stager_#{payload_module_ancestor_factory}" # # Module::Class factories # module_class_factory = "#{factory_namespace}_module_class" context 'CONSTANTS' do context 'PAYLOAD_TYPES' do subject(:payload_types) do described_class::PAYLOAD_TYPES end it { should include('single') } it { should include('staged') } end context 'STAGED_ANCESTOR_PAYLOAD_TYPES' do subject(:staged_ancestor_payload_types) do described_class::STAGED_ANCESTOR_PAYLOAD_TYPES end it { should include('stage') } it { should include('stager') } end end context 'derivations' do context 'with module_type derived' do before(:each) do module_class.module_type = module_class.derived_module_type end context 'with payload_type derived' do before(:each) do module_class.payload_type = module_class.derived_payload_type end context 'with payload module_type' do subject(:module_class) do FactoryGirl.build( module_class_factory, :module_type => 'payload' ) end it_should_behave_like 'derives', :payload_type, :validates => true it_should_behave_like 'derives', :reference_name, :validates => true context 'with payload_type derived' do before(:each) do module_class.payload_type = module_class.derived_payload_type end context 'with reference_name derived' do before(:each) do module_class.reference_name = module_class.derived_reference_name end it_should_behave_like 'derives', :full_name, :validates => true end end end end context 'without payload module_type' do subject(:module_class) do FactoryGirl.build( module_class_factory, :module_type => module_type ) end let(:module_type) do FactoryGirl.generate :metasploit_model_non_payload_module_type end it_should_behave_like 'derives', :reference_name, :validates => true context 'with reference_name derived' do before(:each) do module_class.reference_name = module_class.derived_reference_name end it_should_behave_like 'derives', :full_name, :validates => true end end end it_should_behave_like 'derives', :module_type, :validates => true end context 'search' do context 'attributes' do it_should_behave_like 'search_attribute', :full_name, :type => :string it_should_behave_like 'search_attribute', :module_type, :type => :string it_should_behave_like 'search_attribute', :payload_type, :type => :string it_should_behave_like 'search_attribute', :reference_name, :type => :string end end context 'factories' do context module_class_factory do subject(module_class_factory) do FactoryGirl.build(module_class_factory) end it { should be_valid } context '#ancestors' do subject(:ancestors) do send(module_class_factory).ancestors end context 'Metasploit::Model::Module::Ancestor#contents list' do subject(:contents_list) do ancestors.map(&:contents) end before(:each) do # need to validate so that real_path is derived so contents can be read ancestors.each(&:valid?) end context 'metasploit_modules' do include_context 'Metasploit::Model::Module::Ancestor#contents metasploit_module' subject(:metasploit_modules) do namespace_modules.collect { |namespace_module| namespace_module_metasploit_module(namespace_module) } end let(:namespace_modules) do ancestors.collect { Module.new } end before(:each) do namespace_modules.zip(contents_list) do |namespace_module, contents| namespace_module.module_eval(contents) end end context 'rank_names' do subject(:rank_names) do metasploit_modules.collect { |metasploit_module| metasploit_module.rank_name } end it 'should match Metasploit::Model::Module::Class#rank Metasploit::Model:Module::Rank#name' do rank_names.all? { |rank_name| rank_name == send(module_class_factory).rank.name }.should be_true end end context 'rank_numbers' do subject(:rank_numbers) do metasploit_modules.collect { |metasploit_module| metasploit_module.rank_number } end it 'should match Metasploit::Model::Module::Class#rank Metasploit::Module::Module::Rank#number' do rank_numbers.all? { |rank_number| rank_number == send(module_class_factory).rank.number }.should be_true end end end end end context 'module_type' do subject(module_class_factory) do FactoryGirl.build( module_class_factory, :module_type => module_type ) end context 'with payload' do let(:module_type) do 'payload' end it { should be_valid } context 'with payload_type' do subject(module_class_factory) do FactoryGirl.build( module_class_factory, :module_type => module_type, :payload_type => payload_type ) end context 'single' do let(:payload_type) do 'single' end it { should be_valid } end context 'staged' do let(:payload_type) do 'staged' end it { should be_valid } end context 'other' do let(:payload_type) do 'not_a_payload_type' end it 'should raise ArgumentError' do expect { send(module_class_factory) }.to raise_error(ArgumentError) end end end end context 'without payload' do let(:module_type) do FactoryGirl.generate :metasploit_model_non_payload_module_type end it { should be_valid } its(:derived_module_type) { should == module_type } end end context 'ancestors' do subject(module_class_factory) do FactoryGirl.build( module_class_factory, :ancestors => ancestors ) end context 'single payload' do let!(:ancestors) do [ FactoryGirl.create(single_payload_module_ancestor_factory) ] end it { should be_valid } end context 'stage payload and stager payload' do let!(:ancestors) do [ FactoryGirl.create(stage_payload_module_ancestor_factory), FactoryGirl.create(stager_payload_module_ancestor_factory) ] end it { should be_valid } end end end end context 'validations' do context 'ancestors' do context 'count' do subject(:module_class) do FactoryGirl.build( module_class_factory, :ancestors => ancestors, :module_type => module_type, :payload_type => payload_type ) end before(:each) do # set explicitly so derivation doesn't cause other code path to run module_class.module_type = module_type end context 'with payload module_type' do let(:module_type) do 'payload' end before(:each) do # set explicitly so derivation doesn't cause other code path to run module_class.payload_type = payload_type module_class.valid? end context 'with single payload_type' do let(:error) do 'must have exactly one ancestor for single payload module class' end let(:payload_type) do 'single' end context 'with 1 ancestor' do let(:ancestors) do [ FactoryGirl.create(single_payload_module_ancestor_factory) ] end it 'should not record error on ancestors' do module_class.errors[:ancestors].should_not include(error) end end context 'without 1 ancestor' do let(:ancestors) do [] end it 'should record error on ancestors' do module_class.errors[:ancestors].should include(error) end end end context 'with staged payload_type' do let(:error) do 'must have exactly two ancestors (stager + stage) for staged payload module class' end let(:payload_type) do 'staged' end context 'with 2 ancestors' do let(:ancestors) do [ FactoryGirl.create(stage_payload_module_ancestor_factory), FactoryGirl.create(stager_payload_module_ancestor_factory) ] end it 'should not record error on ancestors' do module_class.errors[:ancestors].should_not include(error) end end context 'without 2 ancestors' do let(:ancestors) do [ FactoryGirl.create(stage_payload_module_ancestor_factory) ] end it 'should record error on ancestors' do module_class.errors[:ancestors].should include(error) end end end end context 'without payload module_type' do let(:error) do 'must have exactly one ancestor as a non-payload module class' end let(:module_type) do FactoryGirl.generate :metasploit_model_non_payload_module_type end let(:payload_type) do nil end before(:each) do module_class.valid? end context 'with 1 ancestor' do let(:ancestors) do [ FactoryGirl.create(non_payload_module_ancestor_factory) ] end it 'should not record error on ancestors' do module_class.errors[:ancestors].should_not include(error) end end context 'without 1 ancestor' do let(:ancestors) do module_class.errors[:ancestors].should include(error) end end end end context 'module_types' do context 'between Metasploit::Model::Module::Ancestor#module_type and Metasploit::Model::Module::Class#module_type' do subject(:module_class) do FactoryGirl.build( module_class_factory, :module_type => module_type, :ancestors => ancestors ) end def error(module_class, ancestor) "can contain ancestors only with same module_type (#{module_class.module_type}); " \ "#{ancestor.full_name} cannot be an ancestor due to its module_type (#{ancestor.module_type})" end before(:each) do # Explicitly set module_type so its not derived, which could cause an alternate code path to be tested module_class.module_type = module_type module_class.valid? end context 'with module_type' do let(:module_type) do FactoryGirl.generate :metasploit_model_module_type end context 'with same Metasploit::Model::Module::Ancestor#module_type and Metasploit::Model::Module::Class#module_type' do let(:ancestors) do [ FactoryGirl.create( module_ancestor_factory, :module_type => module_type ) ] end it 'should not record on ancestors' do module_class.errors[:ancestors].should_not include(error(module_class, ancestors.first)) end end context 'without same Metasploit::Model::Module::Ancestor#module_type and Metasploit::Model::Module::Class#module_type' do let(:ancestors) do [ FactoryGirl.create( module_ancestor_factory, :module_type => 'exploit' ) ] end let(:module_type) do 'nop' end it 'should record error on ancestors' do module_class.errors[:ancestors].should include(error(module_class, ancestors.first)) end end end context 'without module_type' do # with a nil module_type, module_type will be derived from let(:ancestors) do [ FactoryGirl.create(module_ancestor_factory), FactoryGirl.create(module_ancestor_factory) ] end let(:module_type) do nil end it 'should not record errors on ancestors' do ancestor_errors = module_class.errors[:ancestors] ancestors.each do |ancestor| ancestor_error = error(module_class, ancestor) ancestor_errors.should_not include(ancestor_error) end end end end context 'between Metasploit::Model::Module::Ancestor#module_types' do subject(:module_class) do FactoryGirl.build( module_class_factory, :ancestors => ancestors ) end let(:error) do "can only contain ancestors with one module_type, " \ "but contains multiple module_types (#{module_type_set.sort.to_sentence})" end before(:each) do module_class.valid? end context 'with same Metasploit::Model::Module::Ancestor#module_type' do let(:ancestors) do [ FactoryGirl.create( module_ancestor_factory, :module_type => module_type ), FactoryGirl.create( module_ancestor_factory, :module_type => module_type ) ] end let(:module_type) do FactoryGirl.generate :metasploit_model_module_type end let(:module_type_set) do Set.new [module_type] end it 'should not record error on ancestors' do module_class.errors[:ancestors].should_not include(error) end end context 'without same Metasploit::Model::Module::Ancestor#module_type' do let(:ancestors) do module_type_set.collect { |module_type| FactoryGirl.create( module_ancestor_factory, :module_type => module_type ) } end let(:module_types) do [ FactoryGirl.generate(:metasploit_model_module_type), FactoryGirl.generate(:metasploit_model_module_type) ] end let(:module_type_set) do Set.new module_types end it 'should record error on ancestors' do module_class.errors[:ancestors].should include(error) end end end end context 'payload_types' do subject(:module_class) do FactoryGirl.build( module_class_factory, :ancestors => ancestors, :module_type => module_type ) end before(:each) do # explicitly set module_type so it is not derived from ancestors module_class.module_type = module_type end context "with 'payload' Metasploit::Model::Module::Class#module_type" do let(:module_type) do 'payload' end let(:ancestors) do [ ancestor ] end context 'with Metasploit::Model::Module::Class#payload_type' do before(:each) do # Explicitly set payload_type so it is not derived from ancestors module_class.payload_type = payload_type module_class.valid? end context 'single' do let(:error) do "cannot have an ancestor (#{ancestor.full_name}) " \ "with payload_type (#{ancestor.payload_type}) " \ "for class payload_type (#{payload_type})" end let(:payload_type) do 'single' end context "with 'single' Metasploit::Model::Module::Ancestor#payload_type" do let(:ancestor) do FactoryGirl.create(single_payload_module_ancestor_factory) end it 'should not record error on ancestors' do module_class.errors[:ancestors].should_not include(error) end end context "without 'single' Metasploit::Model::Module::Ancestor#payload_type" do let(:ancestor) do FactoryGirl.create(stage_payload_module_ancestor_factory) end it 'should record error on ancestors' do module_class.errors[:ancestors].should include(error) end end end context 'staged' do let(:payload_type) do 'staged' end context "Metasploit::Model::Module::Ancestor#payload_type" do let(:few_error) do "needs exactly one ancestor with payload_type (#{ancestor_payload_type}), " \ "but there are none." end let(:many_error) do "needs exactly one ancestor with payload_type (#{ancestor_payload_type}), " \ "but there are #{ancestors.count} (#{ancestors.map(&:full_name).sort.to_sentence})" end context 'single' do context 'without zero' do let(:ancestor) do FactoryGirl.create(single_payload_module_ancestor_factory) end let(:ancestors) do [ ancestor ] end let(:error) do "cannot have ancestors (#{ancestor.full_name}) " \ "with payload_type (#{ancestor.payload_type}) " \ "for class payload_type (#{payload_type}); " \ "only one stage and one stager ancestor is allowed" end it 'should record error on ancestors' do module_class.valid? module_class.errors[:ancestors].should include(error) end end end context 'stage' do let(:ancestor_payload_type) do 'stage' end context 'with < 1' do # 1 stager and 0 stages, so stages count < 1 let(:ancestors) do [ FactoryGirl.create(stager_payload_module_ancestor_factory) ] end it 'should record error on ancestors' do module_class.errors[:ancestors].should include(few_error) end end context 'with 1' do # 1 stager and 1 stage, so stages count == 1 let(:ancestors) do [ FactoryGirl.create(stager_payload_module_ancestor_factory), FactoryGirl.create(stage_payload_module_ancestor_factory) ] end it 'should not record error on ancestors' do module_class.errors[:ancestors].should_not include(few_error) module_class.errors[:ancestors].should_not include(many_error) end end context 'with > 1' do # 0 stager, 2 stages, so stages count > 1 let(:ancestors) do FactoryGirl.create_list(stage_payload_module_ancestor_factory, 2) end it 'should record error on ancestors' do module_class.errors[:ancestors].should include(many_error) end end end context 'stager' do let(:ancestor_payload_type) do 'stager' end context 'with < 1' do # 0 stager and 1 stages, so stagers count < 1 let(:ancestors) do [ FactoryGirl.create(stage_payload_module_ancestor_factory) ] end it 'should record error on ancestors' do module_class.errors[:ancestors].should include(few_error) end end context 'with 1' do # 1 stager and 1 stage, so stagers count == 1 let(:ancestors) do [ FactoryGirl.create(stager_payload_module_ancestor_factory), FactoryGirl.create(stage_payload_module_ancestor_factory) ] end it 'should not record error on ancestors' do module_class.errors[:ancestors].should_not include(few_error) module_class.errors[:ancestors].should_not include(many_error) end end context 'with > 1' do # 2 stagers, 0 stages, so stagers count > 1 let(:ancestors) do FactoryGirl.create_list(stager_payload_module_ancestor_factory, 2) end it 'should record error on ancestors' do module_class.errors[:ancestors].should include(many_error) end end end end end end end context "without 'payload' Metasploit::Model::Module::Class#module_type" do let(:ancestors) do [ ancestor ] end let(:error) do "cannot have an ancestor (#{ancestor.full_name}) " \ "with a payload_type (#{ancestor.payload_type}) " \ "for class module_type (#{module_type})" end let(:module_type) do FactoryGirl.generate :metasploit_model_non_payload_module_type end before(:each) do module_class.valid? end context 'with Metasploit::Model::Module::Ancestor#payload_type' do let(:ancestor) do FactoryGirl.create(payload_module_ancestor_factory) end it 'should record error on ancestors' do module_class.errors[:ancestors].should include(error) end end context 'without Metasploit::Model::Module::Ancestor#payload_type' do let(:ancestor) do FactoryGirl.create(non_payload_module_ancestor_factory) end it 'should not record error on ancestors' do module_class.errors[:ancestors].should_not include(error) end end end end end context 'validates module_type inclusion in Metasploit::Model::Module::Ancestor::MODULE_TYPES' do subject(:module_class) do FactoryGirl.build( module_class_factory, :ancestors => [], :module_type => module_type ) end let(:error) do 'is not included in the list' end before(:each) do module_class.module_type = module_type end Metasploit::Model::Module::Type::ALL.each do |context_module_type| context "with #{context_module_type}" do let(:module_type) do context_module_type end it 'should not record error on module_type' do module_class.valid? module_class.errors[:module_type].should_not include(error) end end end context 'without module_type' do let(:module_type) do nil end it { should_not be_valid } it 'should record error on module_type' do module_class.valid? module_class.errors[:module_type].should include(error) end end end context 'payload_type' do subject(:module_class) do FactoryGirl.build( module_class_factory, :module_type => module_type ) end before(:each) do module_class.payload_type = payload_type end context 'with payload' do let(:module_type) do 'payload' end context 'with payload_type' do subject(:module_class) do FactoryGirl.build( module_class_factory, # Set explicitly so not derived from module_type and payload_type in factory, which will fail for the # invalid payload_type test. :ancestors => [], :module_type => module_type, :payload_type => payload_type ) end let(:error) do 'is not in list' end before(:each) do # Set explicitly so not derived module_class.payload_type = payload_type end context 'single' do let(:payload_type) do 'single' end it 'should not record error' do module_class.valid? module_class.errors[:payload_type].should_not include(error) end end context 'staged' do let(:payload_type) do 'staged' end it 'should not record error on payload_type' do module_class.valid? module_class.errors[:payload_type].should_not include(error) end end context 'other' do let(:payload_type) do 'invalid_payload_type' end it 'should record error on payload_type' do module_class.valid? module_class.errors[:payload_type].should_not be_empty end end end end context 'without payload' do let(:error) do 'must be nil' end let(:module_type) do FactoryGirl.generate :metasploit_model_non_payload_module_type end before(:each) do module_class.payload_type = payload_type end context 'with payload_type' do let(:payload_type) do FactoryGirl.generate :metasploit_model_module_class_payload_type end it 'should record error on payload_type' do module_class.valid? module_class.errors[:payload_type].should include(error) end end context 'without payload_type' do let(:payload_type) do nil end it 'should not error on payload_type' do module_class.valid? module_class.errors[:payload_type].should_not include(error) end end end end it { should validate_presence_of(:rank) } context 'with nil derived_reference_name' do before(:each) do module_class.stub(:derived_reference_name => nil) end it { should validate_presence_of(:reference_name) } end end context '#derived_module_type' do subject(:derived_module_type) do module_class.derived_module_type end context 'ancestors' do before(:each) do module_class.ancestors = ancestors end context 'empty' do let(:ancestors) do [] end it { should be_nil } end context 'non-empty' do context 'with same Metasploit::Model::Module::Ancestor#module_type' do let(:ancestors) do FactoryGirl.create_list(module_ancestor_factory, 2, :module_type => module_type) end let(:module_type) do FactoryGirl.generate :metasploit_model_module_type end it 'should return shared module_type' do derived_module_type.should == module_type end end context 'with different Metasploit::Model::Module;:Ancestor#module_type' do let(:ancestors) do FactoryGirl.create_list(module_ancestor_factory, 2) end it 'should return nil because there is no consensus' do derived_module_type.should be_nil end end end end end context '#derived_payload_type' do subject(:derived_payload_type) do module_class.derived_payload_type end before(:each) do module_class.module_type = module_type end context 'with payload' do let(:module_type) do 'payload' end before(:each) do module_class.ancestors = ancestors end context 'with 1 ancestor' do let(:ancestors) do [ FactoryGirl.create( module_ancestor_factory, :module_type => 'payload', :payload_type => payload_type ) ] end context 'with single' do let(:payload_type) do 'single' end it { should == 'single' } end context 'without single' do let(:payload_type) do 'stage' end it { should be_nil } end end context 'with 2 ancestors' do context 'with stager and stage' do let(:ancestors) do ['stager', 'stage'].collect { |payload_type| FactoryGirl.create( payload_module_ancestor_factory, :payload_type => payload_type ) } end it { should == 'staged' } end context 'without stager and stage' do let(:ancestors) do FactoryGirl.create_list( payload_module_ancestor_factory, 2, :payload_type => 'stage' ) end it { should be_nil } end end end context 'without payload' do let(:module_type) do FactoryGirl.generate :metasploit_model_non_payload_module_type end end end context '#derived_reference_name' do subject(:derived_reference_name) do module_class.derived_reference_name end before(:each) do module_class.module_type = module_type end context 'with payload' do let(:module_type) do 'payload' end before(:each) do module_class.payload_type = payload_type end context 'with single' do let(:payload_type) do 'single' end it 'should call #derived_single_payload_reference_name' do module_class.should_receive(:derived_single_payload_reference_name) derived_reference_name end end context 'with staged' do let(:payload_type) do 'staged' end it 'should call #derived_staged_payload_reference_name' do module_class.should_receive(:derived_staged_payload_reference_name) derived_reference_name end end context 'without single or staged' do let(:payload_type) do 'invalid_payload_type' end it { should be_nil } end end context 'without payload' do let(:module_type) do FactoryGirl.generate :metasploit_model_non_payload_module_type end before(:each) do module_class.ancestors = ancestors end context 'with 1 ancestor' do let(:ancestor) do FactoryGirl.create(non_payload_module_ancestor_factory) end let(:ancestors) do [ ancestor ] end it 'should return reference_name of ancestor' do derived_reference_name.should == ancestor.reference_name end end context 'without 1 ancestor' do let(:ancestors) do FactoryGirl.create_list(module_ancestor_factory, 2) end it { should be_nil } end end end context '#derived_single_payload_reference_name' do subject(:derived_single_payload_reference_name) do module_class.send(:derived_single_payload_reference_name) end before(:each) do module_class.ancestors = ancestors end context 'with 1 ancestor' do let(:ancestor) do FactoryGirl.create( payload_module_ancestor_factory, :payload_type => payload_type ) end let(:ancestors) do [ ancestor ] end context 'with single' do let(:payload_type) do 'single' end before(:each) do ancestor.reference_name = reference_name end context 'with reference_name' do let(:payload_name) do 'payload/name' end let(:payload_type_directory) do 'singles' end let(:reference_name) do "#{payload_type_directory}/#{payload_name}" end it 'should return Metasploit::Model::Module::Ancestor#payload_name' do expect(derived_single_payload_reference_name).to eq(payload_name) end end context 'without reference_name' do let(:reference_name) do nil end end end context 'without single' do let(:payload_type) do 'stage' end it { should be_nil } end end context 'without 1 ancestor' do let(:ancestors) do [] end it { should be_nil } end end context '#derived_staged_payload_reference_name' do subject(:derived_staged_payload_reference_name) do module_class.send(:derived_staged_payload_reference_name) end before(:each) do module_class.ancestors = ancestors end context 'with 2 ancestors' do context 'with 1 stage' do let(:stage_ancestor) do FactoryGirl.create(stage_payload_module_ancestor_factory) end before(:each) do stage_ancestor.reference_name = stage_reference_name end context 'with reference_name' do let(:stage_payload_name) do 'payload/name' end let(:stage_reference_name) do "#{stage_type_directory}/#{stage_payload_name}" end let(:stage_type_directory) do 'stages' end context 'with 1 stager' do let(:ancestors) do [ stager_ancestor, stage_ancestor ] end let(:stager_ancestor) do FactoryGirl.create(stager_payload_module_ancestor_factory) end before(:each) do stager_ancestor.handler_type = stager_handler_type end context 'with handler_type' do let(:stager_handler_type) do FactoryGirl.generate :metasploit_model_module_handler_type end it 'should be <stage.payload_name>/<stager.handler_type>' do expect(derived_staged_payload_reference_name).to eq("#{stage_payload_name}/#{stager_handler_type}") end end context 'without handler_type' do let(:stager_handler_type) do nil end it { should be_nil } end end context 'without 1 stager' do let(:ancestors) do [ stage_ancestor, FactoryGirl.create(single_payload_module_ancestor_factory) ] end it { should be_nil } end end context 'without reference_name' do let(:ancestors) do [ FactoryGirl.create(stager_payload_module_ancestor_factory), stage_ancestor ] end let(:stage_reference_name) do nil end it { should be_nil } end end context 'without 1 stage' do let(:ancestors) do FactoryGirl.create_list(stager_payload_module_ancestor_factory, 2) end it { should be_nil } end end context 'without 2 ancestors' do let(:ancestors) do FactoryGirl.create_list(module_ancestor_factory, 3) end it { should be_nil } end end context '#payload?' do subject(:payload?) do module_class.payload? end # use new instead of factory so that payload? won't be called in the background to show this context supplies # coverage let(:module_class) do module_class_class.new end before(:each) do module_class.module_type = module_type end context 'with payload' do let(:module_type) do 'payload' end it { should be_true } end context 'without payload' do let(:module_type) do FactoryGirl.generate :metasploit_model_non_payload_module_type end it { should be_false } end end context '#staged_payload_type_count' do subject(:staged_payload_type_count) do module_class.send( :staged_payload_type_count, ancestors_by_payload_type, ancestor_payload_type ) end let(:ancestor_payload_type) do FactoryGirl.generate :metasploit_model_module_ancestor_payload_type end before(:each) do staged_payload_type_count end context 'with ancestors with payload_type' do context 'with 1' do let(:ancestors_by_payload_type) do { ancestor_payload_type => FactoryGirl.create_list( payload_module_ancestor_factory, 1, :payload_type => ancestor_payload_type ) } end it 'should not record error on ancestors' do module_class.errors[:ancestors].should be_empty end end context 'without 1' do let(:ancestors_by_payload_type) do { ancestor_payload_type => payload_type_ancestors } end let(:full_name_sentence) do payload_type_ancestors.map(&:full_name).sort.to_sentence end let(:payload_type_ancestors) do FactoryGirl.create_list( payload_module_ancestor_factory, payload_type_ancestor_count, :payload_type => ancestor_payload_type ) end let(:payload_type_ancestor_count) do 2 end let(:error) do "needs exactly one ancestor with payload_type (#{ancestor_payload_type}), " \ "but there are #{payload_type_ancestor_count} (#{full_name_sentence})" end it 'should record error on ancestors' do module_class.errors[:ancestors].should include(error) end end end context 'without ancestors with payload_type' do let(:ancestors_by_payload_type) do {} end let(:error) do "needs exactly one ancestor with payload_type (#{ancestor_payload_type}), but there are none." end it 'should record error on ancestors' do module_class.errors[:ancestors].should include(error) end end end end
require "slim" require "colorize" require "jazz/version" require "jazz/parser" require "jazz/slim" require "jazz/uberlogger" require "jazz/scope" require "jazz/method" require "parallel" include Jazz::UberLogger # Ruby really should abort on unhandled exceptions by default... Thread.abort_on_exception = true class Object def deep_map(&block) block.call(self) end end class Array def deep_map(&block) map { |e| e.deep_map(&block) } end end class Sexp def parallel_deep_each(&block) self.parallel_each_sexp do |sexp| block[sexp] sexp.parallel_deep_each(&block) end end def parallel_each_sexp Parallel.each(self, :in_threads => Parallel.processor_count) do |sexp| new_sexp = ::Sexp.from_array(sexp) p sexp next unless Sexp === new_sexp yield new_sexp end end end
require 'spec_helper' require 'natives/catalog' describe Natives::Catalog do describe "#new" do it "loads catalogs" do Natives::Catalog.any_instance.should_receive(:reload) Natives::Catalog.new('rubygems', 'mac_os_x', '10.7.5', 'homebrew') end it "requires caller to provide platform and package provider details" do catalog = Natives::Catalog.new('rubygems', 'mac_os_x', '10.7.5', 'homebrew') expect(catalog.name).to eq('rubygems') expect(catalog.platform).to eq('mac_os_x') expect(catalog.platform_version).to eq('10.7.5') expect(catalog.package_provider).to eq('homebrew') end end describe "#reload" do it "reloads catalogs from default catalog paths" do loader = double() loader. should_receive(:load_from_paths). with([ Natives::Catalog::CATALOG_PATH_IN_GEM, File.absolute_path(File.join(Dir.pwd, 'natives-catalogs')) ]). and_return({ 'rubygems' => {'foo' => {'key' => 'value'}}, 'npm' => {'bar' => {'key' => 'value'}} }) catalog = Natives::Catalog.new('rubygems', 'mac_os_x', '10.7.5', 'homebrew', loader: loader) expect(catalog.to_hash).to eq({'foo' => {'key' => 'value'}}) end it "reloads catalogs from given working directory" do loader = double() loader. should_receive(:load_from_paths). with([ Natives::Catalog::CATALOG_PATH_IN_GEM, '/path/to/working_dir/natives-catalogs' ]). and_return({ 'rubygems' => {'foo' => {'key' => 'value'}}, 'npm' => {'bar' => {'key' => 'value'}} }) catalog = Natives::Catalog.new('rubygems', 'mac_os_x', '10.7.5', 'homebrew', loader: loader, working_dir: '/path/to/working_dir') expect(catalog.to_hash).to eq({'foo' => {'key' => 'value'}}) end end describe "#to_hash" do before do Natives::Catalog::Loader.any_instance. stub(:load_from_paths). and_return({ 'rubygems' => {'foo' => {'key' => 'value'}}, 'npm' => {'bar' => {'key' => 'value'}} }) end it "returns catalog hash of the specified catalog name" do catalog = Natives::Catalog.new("npm", nil, nil, nil) expect(catalog.to_hash).to eq({'bar' => {'key' => 'value'}}) end it "returns empty hash if the sepcified catalog not found" do catalog = Natives::Catalog.new("notfound", nil, nil, nil) expect(catalog.to_hash).to eq({}) end end describe "#native_packages_for" do before do Natives::Catalog::Loader.any_instance. stub(:load_from_paths). and_return({ 'rubygems' => { 'nokogiri' => { 'apt' => { 'ubuntu' => { '13.10' => 'value1', 'default' => 'value2' } } }, 'curb' => { 'apt' => { 'ubuntu' => { 'default' => 'value3' } } } }, }) end it "returns native packages for the given catalog entry name" do catalog = Natives::Catalog.new(:rubygems, 'ubuntu', '13.10', 'apt') expect(catalog.native_packages_for('nokogiri')).to eq(['value1']) end it "returns empty list if the given catalog entry name does not exist" do catalog = Natives::Catalog.new(:rubygems, 'ubuntu', '13.10', 'apt') expect(catalog.native_packages_for('notfound')).to eq([]) end it "return native packages for the given catalog entry name list" do catalog = Natives::Catalog.new(:rubygems, 'ubuntu', '13.10', 'apt') expect(catalog.native_packages_for( 'nokogiri', 'notfound', 'curb')).to eq(['value1', 'value3']) end it "return native packages for the given catalog entry name array" do catalog = Natives::Catalog.new(:rubygems, 'ubuntu', '13.10', 'apt') expect(catalog.native_packages_for( ['nokogiri', 'notfound', 'curb'])).to eq(['value1', 'value3']) end end end
class MapsController < ApplicationController def index @user = current_user end def new @map = Map.new() @user = current_user end def create @map = Map.new(map_params) p @map @map.user_id = current_user.id respond_to do |format| if @map.save @event = Songkick::Calendar.new(artist_name: @map.artist) format.json { render :json, { locations: @event.tour_locations, artist: @map.artist, titles: @event.event_titles, dates: @event.event_dates, times: @event.event_times, links: @event.event_links, cities: @event.cities } } end end end def show @map = Map.find(params[:id]) p "&" * 70 p @map.artist p "&" * 70 p @map.center_lat respond_to do |format| format.json { render json: { center_lat: @map.center_lat, center_lng: @map.center_lng, locations: @event.tour_locations, artist: @map.artist, titles: @event.event_titles, dates: @event.event_dates, times: @event.event_times, links: @event.event_links, cities: @event.cities } } format.html end end def edit end def update end def destroy @map = Map.find(params[:id]) @map.destroy redirect_to user_maps_path(current_user) end private def map_params params.require(:map).permit(:center_lat, :center_lng, :artist, :user_id) end end
require 'sinatra/base' require 'json' require_relative './lib/data.rb' class ThermoNuclearServer < Sinatra::Base enable :sessions set :session_secret, 'fsddsgjk22' before do @datastorage = NuclearData.instance end get '/' do headers 'Access-Control-Allow-Origin' => '*' {temp: @datastorage.temp, mode: @datastorage.mode}.to_json end post '/' do headers 'Access-Control-Allow-Origin' => '*' @datastorage.temp = params[:temperature] @datastorage.mode = params[:mode] redirect '/' end end
require "rom" require "rom/memory" describe "ROM integration" do before do class UserMapper < Faceter::Mapper group :email, to: :emails list do field :emails do list { unfold from: :email } end end end # Set ROM environment ROM.use :auto_registration setup = ROM.setup :memory setup.relation(:users) setup.mappers do register(:users, mapped: UserMapper.new) end users = setup.default.dataset(:users) users.insert(id: 1, name: "Joe", email: "joe@doe.com") users.insert(id: 1, name: "Joe", email: "joe@doe.org") ROM.finalize end let(:rom) { ROM.env } let(:users) { rom.relation(:users) } it "works" do expect(users.as(:mapped).to_a) .to eql [{ id: 1, name: "Joe", emails: ["joe@doe.com", "joe@doe.org"] }] end after { Object.send :remove_const, :UserMapper } end # describe "ROM integration"
RSpec.describe MonstersController do describe "GET index" do it "blocks unauthenticated access" do get :index, format: :json expect(response.body).to eq({user: :invalid}.to_json) end context 'with login' do before do @user = create(:user) @monster = create(:monster, user: @user, category: 'fire') sign_in @user end it "should return monsters json" do get :index, format: :json expected_response = {success: true, monsters: [@monster].as_json} expect(response.body).to eq(expected_response.to_json) end it "should return ordered monsters json" do @monster2 = create(:monster, user: @user, category: 'earth') get :index, order: {category: 'desc'}, format: :json expected_response = {success: true, monsters: [@monster, @monster2].as_json} expect(response.body).to eq(expected_response.to_json) end end end describe "#create" do it "blocks unauthenticated access" do sign_in nil post :create, monster: {name: 'Monster1'}, format: :json expect(response.body).to eq({user: :invalid}.to_json) end context 'with login' do before do @user = create(:user) sign_in @user end it "creates a monster" do post :create, monster: attributes_for(:monster), format: :json expected_response = {success: true, monster: Monster.last.as_json} expect(response.body).to eq(expected_response.to_json) end end end describe "#update" do it "blocks unauthenticated access" do sign_in nil post :update, id: 1, monster: attributes_for(:monster), format: :json expect(response.body).to eq({user: :invalid}.to_json) end context 'with login' do before do @user = create(:user) sign_in @user @monster = create(:monster, user: @user) end it "creates a monster" do post :update, id: @monster.id, monster: {name: 'Monster1o1'}, format: :json expected_response = {success: true, monster: Monster.last.as_json} expect(response.body).to eq(expected_response.to_json) end end end describe "#destroy" do it "blocks unauthenticated access" do sign_in nil delete :destroy, id: 1, format: :json expect(response.body).to eq({user: :invalid}.to_json) end context 'with login' do before do @user = create(:user) sign_in @user @monster = create(:monster, user: @user) end it "destroy the monster" do delete :destroy, id: @monster.id, format: :json expected_response = {success: true} expect(response.body).to eq(expected_response.to_json) end end end end
#!/usr/bin/env ruby # Given an alphabet (alph) returns number of permutations of n digits, # organized by the order established in alph # opens input.txt and formats input parameters alph, num = File.open("rosalind_lexf.txt", "rb").readlines alph.rstrip! alph = alph.split(' ') num = num.to_i def generate_order(array) # Generates hash_value used to order text value_hash = Hash.new{} array.each_with_index {|item, index| value_hash[item] = (array.size - index)} value_hash end def k_mer(alph, num) # Create permutations perm = alph.permutation(num).to_a # Insert self-pairs alph.each{|element| perm << [element]* num} value_hash = generate_order(alph) perm.each do |element| total_val = 0 element.each_with_index{|value, index| total_val += value_hash[value]*(10**-(index))} element << total_val end # Sorts by value_hash element perm.sort_by!{|x| x.last}.reverse! perm.map! do |element| # Removes final element and joins individual elements into final string element = element[0..-2] element.join end perm end def print_all(perm) #prints all in better format and puts into output file output = File.open("output.txt", "w") output << perm.each{|element| print element.to_s + "\n"} output.close end print_all(k_mer(alph, num)) # alph = ['T', 'A', 'G', 'C'] # num = 2 # test_block = Proc.new {k_mer()} # print test_block.call() if __FILE__ == $0
class UserMailer < ActionMailer::Base helper :application default from: "EnerSerial@eneraque.com" def update_pm(user, job, current_user) @user = user @url = 'http://enerserial.eneraque.com/users/sign_in' @job_url = "http://enerserial.eneraque.com/jobs/#{job.id}" @job = job @current_user = current_user mail(to: @user.email, subject: "You've been assigned PM of a Serial Number Register item.") end def status_update(user, stock, current_user) @user = user @url = 'http://enerserial.eneraque.com/users/sign_in' @stock = stock @stock_url ="http://enerserial.eneraque.com/stocks/#{@stock.id}" @current_user = current_user @job_number = @stock.job.job_number mail(to: @user.email, subject: "Stock Item has been marked as #{@stock.status}.") end def jim_status_update(stock, current_user) @url = 'http://enerserial.eneraque.com/users/sign_in' @stock = stock @stock_url ="http://enerserial.eneraque.com/stocks/#{@stock.id}" @current_user = current_user mail(to: "jim.pringle@eneraque.com", subject: "Stock Item has been marked as #{@stock.status}.") end def production_notify_accounts(stock, user) @current_user = user @url = stock_path(stock) @stock = stock @stock_url ="http://enerserial.eneraque.com/stocks/#{@stock.id}" mail(to: 'accounts@eneraque.com', subject: "Stock Item Completed: Accounting Checkoff") end def production_notify_pm(stock, user) @current_user = user @url = stock_path(stock) @stock = stock @stock_url ="http://enerserial.eneraque.com/stocks/#{@stock.id}" mail(to: @stock.job.user.email, subject: "Stock Item Completed: PM Checkoff") end end
class CreateExcludedAdHocOptionValues < ActiveRecord::Migration[4.2] def self.up create_table :excluded_ad_hoc_option_values do |t| t.integer :ad_hoc_variant_exclusion_id t.integer :ad_hoc_option_value_id end end def self.down drop_table :excluded_ad_hoc_option_values end end
require 'test_helper' class Admin::Api::ServicesTest < ActionDispatch::IntegrationTest def setup @provider = FactoryBot.create :provider_account, :domain => 'provider.example.com' @service = FactoryBot.create(:service, :account => @provider) host! @provider.admin_domain end # Access token test 'show (access_token)' do User.any_instance.stubs(:has_access_to_all_services?).returns(false) user = FactoryBot.create(:member, account: @provider, admin_sections: ['partners']) token = FactoryBot.create(:access_token, owner: user, scopes: 'account_management') get(admin_api_service_path(@service)) assert_response :forbidden get(admin_api_service_path(@service), access_token: token.value) assert_response :not_found User.any_instance.expects(:member_permission_service_ids).returns([@service.id]).at_least_once get(admin_api_service_path(@service), access_token: token.value) assert_response :success end # Provider key test 'index' do get admin_api_services_path, :provider_key => @provider.api_key, :format => :xml assert_response :success assert_services @response.body, { :account_id => @provider.id } end test 'show' do get admin_api_service_path(@service), :provider_key => @provider.api_key, :format => :xml assert_response :success assert_service @response.body, {:account_id => @provider.id, :id => @service.id} end pending_test 'show with wrong id' do end test 'create' do Settings::Switch.any_instance.stubs(:allowed?).returns(true) post(admin_api_services_path, :provider_key => @provider.api_key, :format => :xml, :name => 'service foo') assert_response :success assert_service(@response.body, { :account_id => @provider.id, :name => "service foo" }) assert @provider.services.find_by_name("service foo") end test 'create with json body parameters' do @provider.settings.allow_multiple_services! @provider.provider_constraints.update_attributes!(max_services: 5) assert_difference @provider.services.method(:count) do post(admin_api_services_path(provider_key: @provider.api_key), { name: 'foo' }.to_json, { 'CONTENT_TYPE' => 'application/json' }) assert_response :success end end test 'create fails without multiple_services switch' do post(admin_api_services_path, :provider_key => @provider.api_key, :format => :xml, :name => 'service foo') assert_response :forbidden end test 'update' do put("/admin/api/services/#{@service.id}", :provider_key => @provider.api_key, :format => :xml, :name => 'new service name') assert_response :success assert_service(@response.body, { :account_id => @provider.id, :name => "new service name" }) @service.reload assert @service.name == "new service name" end test 'update the support email' do put(admin_api_service_path(@service), provider_key: @provider.api_key, :format => :xml, support_email: 'supp@topo.com') assert_response :success @service.reload assert_equal 'supp@topo.com', @service.support_email end pending_test 'update with wrong id' do end test 'destroy' do # Creating at least two services so that one service still remains @provider.settings.allow_multiple_services! _other_service = FactoryBot.create(:simple_service, account: @provider) access_token = FactoryBot.create(:access_token, owner: @provider.admins.first, scopes: 'account_management') delete admin_api_service_path @service.id, access_token: access_token.value, format: :json assert_response 200 assert_raise(ActiveRecord::RecordNotFound) { Service.accessible.find(@service.id) } end class WithReadOnlyTokenTest < ActionDispatch::IntegrationTest disable_transactional_fixtures! def setup @provider = FactoryBot.create :provider_account, :domain => 'provider.example.com' @service = FactoryBot.create(:service, :account => @provider) host! @provider.admin_domain end test 'update with a ro token fails' do user = FactoryBot.create(:simple_admin, account: @provider) ro_token = FactoryBot.create(:access_token, owner: user, scopes: 'account_management', permission: 'ro') rw_token = FactoryBot.create(:access_token, owner: user, scopes: 'account_management', permission: 'rw') put("/admin/api/services/#{@service.id}", access_token: rw_token.value, format: :xml, name: 'new service name') assert_response :success @service.reload assert_equal 'new service name', @service.name put("/admin/api/services/#{@service.id}", access_token: ro_token.value, format: :xml, name: 'other service name') assert_response :forbidden @service.reload assert_equal 'new service name', @service.name end end end
require 'rspec/core/shared_example_group' # Helper methods for running specs for metasploit-model. module Metasploit::Model::Spec extend ActiveSupport::Autoload autoload :Error autoload :I18nExceptionHandler autoload :PathnameCollision autoload :Template autoload :TemporaryPathname extend Metasploit::Model::Spec::TemporaryPathname # without this, Module.shared_examples_for will be used and RSpec will count shared_examples created with # {shared_examples_for} to not be declared at the top-level. extend RSpec::Core::SharedExampleGroup::TopLevelDSL # Defines a shared examples for a `Module` under the {Metasploit::Model} namespace. This `Module` is assumed to # be a mixin that can be mixed into an ActiveModel in metasploit-framework or an ActiveRecord in # metasploit_data_models. Shared examples declared using this method get access to boiler plate methods used # for all the {Metasploit::Model} mixin `Modules`: # # * <relative_variable_name>_class # * <relative_variable_name>_factory # * factory_namespace # * relative_variable_name # * #<relative_variable_name>_class # * #<relative_variable_name>_factory # # @example boiler plate methods for Module::Ancestor # # defined shared example's name will be 'Metasploit::Model::Module::Ancestor', but you only need to give the # # name relative to 'Metasploit::Model'. # Metasploit::Model::Spec.shared_examples_for 'Module::Ancestor' do # module_ancestor_class # '<namespace_name>::Module::Ancestor' # module_ancestor_factory # '<factory_namespace>_module_ancestor' # factory_namespace # namespace_name converted to underscore with / replaced by _ # relative_variable_name # 'module_ancestor' # # let(:base_class) do # automatically defined for you # module_ancestor_class # same as class method module_ancestor_class # end # # context 'factories' do # have to define this yourself since not all mixins use factories. # context module_ancestor_factory do # using class method # subject(module_ancestor_factory) do # using class method # FactoryGirl.build(module_ancestor_factory) # using instance method # end # end # end # end # # @example Using shared example # describe Metasploit::Model::Module::Ancestor do # it_should_behave_like 'Metasploit::Model::Module::Ancestor', # namespace_name: 'Dummy' # end # # @param relative_name [String] name relative to 'Metasploit::Model' prefix. For example, to declare # 'Metasploit::Model::Module::Ancestor' shared example, `relative_name` would be just 'Module::Ancestor'. # @yield Body of shared examples. # @yieldreturn [void] # @return [void] def self.shared_examples_for(relative_name, &block) fully_qualified_name = "Metasploit::Model::#{relative_name}" relative_variable_name = relative_name.underscore.gsub('/', '_') class_method_name = "#{relative_variable_name}_class" factory_method_name = "#{relative_variable_name}_factory" # capture block to pass to super so that source_location can be overridden to be block's source_location so that # errors are reported correctly from RSpec. wrapper = ->(options={}) { options.assert_valid_keys(:namespace_name) namespace_name = options.fetch(:namespace_name) class_name = "#{namespace_name}::#{relative_name}" # # Singleton methods to emulate local variable used to define examples and lets # define_singleton_method(class_method_name) do class_name.constantize end define_singleton_method(factory_method_name) do "#{factory_namespace}_#{relative_variable_name}" end define_singleton_method(:factory_namespace) do namespace_name.underscore.gsub('/', '_') end define_singleton_method(:namespace_name) do namespace_name end define_singleton_method(:relative_variable_name) do relative_variable_name end # # Defines to emulate local variable used inside lets # define_method(class_method_name) do self.class.send(class_method_name) end define_method(factory_method_name) do self.class.send(factory_method_name) end # # Default subject uses factory # subject(relative_variable_name) do FactoryGirl.build(send(factory_method_name)) end # # lets # let(:base_class) do self.class.send(class_method_name) end it_should_behave_like 'Metasploit::Model::Translation', metasploit_model_ancestor: fully_qualified_name.constantize module_eval(&block) } # Delegate source_location so that RSpec will report block's source_location as the declaration location of # the shared location instead of this method. wrapper.define_singleton_method(:source_location) do block.source_location end super(fully_qualified_name, &wrapper) end end
# Definition for singly-linked list. # class ListNode # attr_accessor :val, :next # def initialize(val) # @val = val # @next = nil # end # end # @param {ListNode} headA # @param {ListNode} headB # @return {ListNode} def getIntersectionNode(headA, headB) return nil if headA == nil || headB == nil pointer_a = headA pointer_b = headB while(pointer_a != pointer_b) if(pointer_a == nil) pointer_a = headB else pointer_a = pointer_a.next end if(pointer_b == nil) pointer_b = headA else pointer_b = pointer_b.next end end return pointer_a end
class IncidentsubcategoriesController < ApplicationController before_action :set_incidentsubcategory, only: [:show, :edit, :update, :destroy] # GET /incidentsubcategories # GET /incidentsubcategories.json def index @incidentsubcategories = Incidentsubcategory.all end # GET /incidentsubcategories/1 # GET /incidentsubcategories/1.json def show end # GET /incidentsubcategories/new def new @incidentsubcategory = Incidentsubcategory.new end # GET /incidentsubcategories/1/edit def edit end # POST /incidentsubcategories # POST /incidentsubcategories.json def create @incidentsubcategory = Incidentsubcategory.new(incidentsubcategory_params) respond_to do |format| if @incidentsubcategory.save format.html { redirect_to @incidentsubcategory.incidentcategory, notice: 'Incidentsubcategory was successfully created.' } format.json { render :show, status: :created, location: @incidentsubcategory } else format.html { render :new } format.json { render json: @incidentsubcategory.errors, status: :unprocessable_entity } end end end # PATCH/PUT /incidentsubcategories/1 # PATCH/PUT /incidentsubcategories/1.json def update respond_to do |format| if @incidentsubcategory.update(incidentsubcategory_params) format.html { redirect_to @incidentsubcategory.incidentcategory, notice: 'Incidentsubcategory was successfully updated.' } format.json { render :show, status: :ok, location: @incidentsubcategory } else format.html { render :edit } format.json { render json: @incidentsubcategory.errors, status: :unprocessable_entity } end end end # DELETE /incidentsubcategories/1 # DELETE /incidentsubcategories/1.json def destroy incidentcategory = @incidentsubcategory.incidentcategory @incidentsubcategory.destroy respond_to do |format| format.html { redirect_to incidentcategory, notice: 'Incidentsubcategory was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_incidentsubcategory @incidentsubcategory = Incidentsubcategory.find(params[:id]) end # Only allow a list of trusted parameters through. def incidentsubcategory_params params.require(:incidentsubcategory).permit(:incidentcategory_id, :name) end end
# frozen_string_literal: true if Settings.carrierwave.storage == "file" CarrierWave.configure do |config| config.storage = :file end elsif Settings.carrierwave.storage == "aws" CarrierWave.configure do |config| config.storage = :aws config.aws_bucket = Settings.carrierwave.aws_bucket config.aws_acl = Settings.carrierwave.aws_acl config.asset_host = Settings.carrierwave.asset_host config.aws_attributes = { expires: Settings.carrierwave.aws_attributes.expires, cache_control: Settings.carrierwave.aws_attributes.cache_control } config.aws_credentials = { region: Settings.carrierwave.aws_credentials.region, access_key_id: Settings.carrierwave.aws_credentials.aws_access_key_id, secret_access_key: Settings.carrierwave.aws_credentials.aws_secret_access_key } end end
# frozen_string_literal: true module SeedsHelper # rubocop:disable Rails/Output def self.count_records_for(model) puts "Seeding #{model.table_name}" starting_record_count = model.count starting_time = Time.zone.now yield ending_count = model.count puts " -> #{ending_count - starting_record_count} new" puts " -> #{ending_count} total" puts " -> #{(Time.zone.now - starting_time).round(3)}s" end # rubocop:enable Rails/Output end
require 'hand' describe Hand do subject(:hand) { Hand.new } subject(:empty_hand) { Hand.new } let(:card1) { double("card1") } let(:card2) { double("card2") } let(:card3) { double("card3") } let(:jack_club) { double("jack_club", suit: :club, value: :jack) } let(:ten_club) { double("ten_club", suit: :club, value: :ten) } let(:nine_club) { double("nine_club", suit: :club, value: :nine) } let(:eight_club) { double("eight_club", suit: :club, value: :eight) } let(:seven_club) { double("seven_club", suit: :club, value: :seven) } let(:five_spade) { double("five_spade", suit: :spade, value: :five) } it 'initializes as an empty array' do expect(hand.cards).to be_empty end describe '#receive_card' do before do hand.receive_card(card1) hand.receive_card(card2) hand.receive_card(card3) end it 'receives cards' do expect(hand.cards).to include(card1) expect(hand.cards).to include(card2) expect(hand.cards).to include(card3) end end describe '#discard_card' do context 'Hand is empty' do it 'empty hand should throw an error' do expect { hand.discard_card(card1) }.to raise_error(NoSuchCardError) end end context 'Hand not empty' do before do hand.receive_card(card1) hand.receive_card(card2) end it 'should remove the card specified from hand' do hand.discard_card(card1) expect(hand.cards).not_to include(card1) end it 'should remove the card specified from hand' do expect { hand.discard_card(card3) }.to raise_error(NoSuchCardError) end end end describe '#straight_flush?' do before do hand.receive_card(jack_club) hand.receive_card(ten_club) hand.receive_card(nine_club) hand.receive_card(eight_club) end it 'returns true if the hand is a straight flush' do hand.receive_card(seven_club) expect(hand.straight_flush?).to be true end it 'returns true if the hand is a straight flush' do hand.receive_card(five_spade) expect(hand.straight_flush?).to be false end end end
require "app_up/hooks/hook" module AppUp module Hooks class Hook < Struct.new(:shell, :files, :options) def self.run(shell, files, options) new(shell, files, options).run end def run raise "Must be implemented" end end end end
class PlacesController < ApplicationController def index @places = Place.order('name') end def map end def show set_place end private def set_place @place = Place.find_by(url_name: params[:id]) end end
require_relative 'buddycloud-build-notification' class BuddycloudNotification < Jenkins::Tasks::Publisher attr_reader :api_base_url, :username, :password, :channel, :send_success_notifications, :success_message, :send_unstable_notifications, :unstable_message, :send_failure_notifications, :failure_message, :send_status_update, :success_status_message, :unstable_status_message, :failure_status_message display_name 'buddycloud Notification' def initialize(attrs) attrs.each { |k, v| instance_variable_set "@#{k}", v } end def perform(build, launcher, listener) n = BuddycloudBuildNotification.new build, listener, self return unless n.should_send_notification? listener.info 'Sending buddycloud notification...' begin n.send_notification listener.info 'buddycloud notification sent.' rescue => e listener.error ['An error occurred while sending the buddycloud notification.', e.message, e.backtrace] * "\n" end end end
class CategoriesIndicator < ActiveRecord::Base belongs_to :indicator, touch: true belongs_to :category end
#!/usr/bin/env ruby class Tmux class Battery SYMBOLS = { :charging => ["21c8".hex].pack("U*"), :discharging => ["21ca".hex].pack("U*"), } def initialize @output = `pmset -g batt`.strip.split("\n") parse! end def run case @state when :charging puts " #{@time} #{SYMBOLS[:charging]} " when :discharging puts " #{@time} #{SYMBOLS[:discharging]} " end end private def parse! if @output.first.include? 'AC Power' @source = :ac else @source = :battery end data = @output.last.strip.squeeze(' ').split(' ') @percert = data[1][0..-3] @state = data[2][0..-2].to_sym @time = data[3] == '(no' ? '...' : data[3] end end end Tmux::Battery.new.run
class HomeController < ApplicationController def home mg_client = Mailgun::Client.new 'key-37da36884b26bd3e362eaafccf989eb8' message_params = {from: 'Mailgun Sandbox <postmaster@sandboxd7bc03e1757d4439ab1805e09a6e8bf7.mailgun.org>', to: 'Kelton Manzanares <kelton.manzanares@gmail.com>', subject: 'The Ruby SDK is awesome!', text: 'It is really easy to send a message!'} mg_client.send_message 'sandboxd7bc03e1757d4439ab1805e09a6e8bf7.mailgun.org', message_params end end
class InitialLayout < ActiveRecord::Migration def self.up create_table "addresses", :force => true do |t| #table used to be :users t.integer "user_id", :null => false #used to be :maia_user_id t.integer "policy_id", :default => 1, :null => false t.integer "domain_id", :null => false t.integer "priority", :default => 7, :null => false t.string "email", :null => false end add_index "addresses", ["email"], :name => "email", :unique => true add_index "addresses", ["user_id"], :name => "addresses_idx_user_id" create_table "awl", :id => false, :force => true do |t| t.string "username", :limit => 100, :default => "", :null => false t.string "email", :limit => 200, :default => "", :null => false t.string "ip", :limit => 10, :default => "", :null => false t.integer "count", :default => 0 t.float "totscore", :default => 0.0 end create_table "banned_attachments", :force => true do |t| t.integer "message_id", :null => false t.string "file_name", :null => false t.string "file_type", :limit => 20, :default => "Unknown", :null => false end add_index "banned_attachments", ["message_id", "file_name"], :name => "mail_file", :unique => true create_table "bayes_expire", :id => false, :force => true do |t| t.integer "id", :default => 0, :null => false t.integer "runtime", :default => 0, :null => false end add_index "bayes_expire", ["id"], :name => "bayes_expire_idx1" create_table "bayes_global_vars", :primary_key => "variable", :force => true do |t| t.string "value", :limit => 200, :default => "", :null => false end create_table "bayes_seen", :id => false, :force => true do |t| t.integer "id", :default => 0, :null => false t.string "msgid", :limit => 200, :default => "", :null => false t.string "flag", :limit => 1, :default => "", :null => false end create_table "bayes_token", :id => false, :force => true do |t| t.integer "id", :default => 0, :null => false t.string "token", :limit => 5, :default => "", :null => false t.integer "spam_count", :default => 0, :null => false t.integer "ham_count", :default => 0, :null => false t.integer "atime", :default => 0, :null => false end add_index "bayes_token", ["id", "atime"], :name => "bayes_token_idx2" add_index "bayes_token", ["token"], :name => "bayes_token_idx1" create_table "bayes_vars", :force => true do |t| t.string "username", :limit => 200, :default => "", :null => false t.integer "spam_count", :default => 0, :null => false t.integer "ham_count", :default => 0, :null => false t.integer "token_count", :default => 0, :null => false t.integer "last_expire", :default => 0, :null => false t.integer "last_atime_delta", :default => 0, :null => false t.integer "last_expire_reduce", :default => 0, :null => false t.integer "oldest_token_age", :default => 2147483647, :null => false t.integer "newest_token_age", :default => 0, :null => false end add_index "bayes_vars", ["username"], :name => "bayes_vars_idx1", :unique => true create_table "detected_viruses", :force => true do |t| t.integer "message_id", :null => false t.integer "virus_id", :null => false end add_index "detected_viruses", ["message_id", "virus_id"], :name => "mail_virus_idx", :unique => true create_table "domains", :force => true do |t| t.string "domain", :null => false t.integer "language_id", :default => 1, :null => false t.boolean "reminders", :default => false, :null => false t.boolean "charts", :default => false, :null => false t.boolean "enable_user_autocreation", :default => true, :null => false t.string "charset", :limit => 20, :default => "ISO-8859-1", :null => false end add_index "domains", ["domain"], :name => "domain", :unique => true create_table "domain_admins", :force => true do |t| t.integer "domain_id", :null => false t.integer "user_id", :null => false end add_index "domain_admins", ["domain_id", "user_id"], :name => "domain_admin", :unique => true create_table "languages", :force => true do |t| t.string "language_name", :limit => 100, :null => false t.string "abbreviation", :limit => 2, :null => false t.boolean "installed", :default => false, :null => false end add_index "languages", ["abbreviation"], :name => "abbreviation", :unique => true create_table "messages", :force => true do |t| t.datetime "received_date", :null => false t.integer "size", :null => false t.string "sender_email", :null => false t.text "envelope_to", :null => false t.string "subject", :null => false t.text "contents", :null => false t.float "score" end add_index "messages", ["received_date"], :name => "message_idx_received_date" create_table "policies", :force => true do |t| t.string "policy_name" t.boolean "virus_lover", :default => true t.boolean "spam_lover", :default => true t.boolean "banned_files_lover", :default => true t.boolean "bad_header_lover", :default => true t.boolean "bypass_virus_checks", :default => true t.boolean "bypass_spam_checks", :default => true t.boolean "bypass_banned_checks", :default => true t.boolean "bypass_header_checks", :default => true t.boolean "discard_viruses", :default => false t.boolean "discard_spam", :default => false t.boolean "discard_banned_files", :default => false t.boolean "discard_bad_headers", :default => false t.boolean "spam_modifies_subj", :default => false t.string "spam_quarantine_to", :limit => 64 t.float "spam_tag_level", :default => 999.0 t.float "spam_tag2_level", :default => 999.0 t.float "spam_kill_level", :default => 999.0 end create_table "recipients", :force => true do |t| t.integer "message_id", :null => false t.integer "address_id", :null => false t.string "scanned_type", :limit => 1, :null => false t.string "token", :limit => 64, :null => false end add_index "recipients", ["message_id", "address_id"], :name => "mail_recipient", :unique => true add_index "recipients", ["address_id"], :name => "recipients_idx_address_id" add_index "recipients", ["scanned_type"], :name => "recipients_idx_type" add_index "recipients", ["token"], :name => "token_system_idx", :unique => true create_table "rules", :force => true do |t| t.string "rule_name", :null => false t.string "rule_description", :default => "", :null => false t.float "rule_score_0", :default => 1.0, :null => false t.float "rule_score_1", :default => 1.0, :null => false t.float "rule_score_2", :default => 1.0, :null => false t.float "rule_score_3", :default => 1.0, :null => false t.integer "rule_count", :default => 0, :null => false end add_index "rules", ["rule_name"], :name => "rule_name", :unique => true create_table "senders", :force => true do |t| t.integer "priority", :default => 7, :null => false t.string "email", :null => false end add_index "senders", ["email"], :name => "senders_email", :unique => true create_table "settings", :force => true do |t| t.boolean "enable_user_autocreation", :default => false, :null => false t.boolean "enable_false_negative_management", :default => true, :null => false t.boolean "enable_stats_tracking", :default => true, :null => false t.boolean "enable_virus_scanning", :default => true, :null => false t.boolean "enable_spam_filtering", :default => true, :null => false t.boolean "enable_banned_files_checking", :default => true, :null => false t.boolean "enable_bad_header_checking", :default => true, :null => false t.boolean "enable_charts", :default => false, :null => false t.boolean "enable_spamtraps", :default => false, :null => false t.boolean "enable_stats_reporting", :default => false, :null => false t.boolean "enable_address_linking", :default => true, :null => false t.boolean "enable_privacy_invasion", :default => false, :null => false t.boolean "enable_username_changes", :default => true, :null => false t.boolean "internal_auth", :default => false, :null => false t.boolean "system_default_user_is_local", :default => true, :null => false t.boolean "user_virus_scanning", :default => true, :null => false t.boolean "user_spam_filtering", :default => true, :null => false t.boolean "user_banned_files_checking", :default => true, :null => false t.boolean "user_bad_header_checking", :default => true, :null => false t.string "admin_email" t.integer "expiry_period", :default => 30 t.integer "ham_cache_expiry_period", :default => 5 t.integer "reminder_threshold_count", :default => 100 t.integer "reminder_threshold_size", :default => 500000 t.string "reminder_template_file", :default => "reminder.tpl" t.string "reminder_login_url" t.string "newuser_template_file", :default => "newuser.tpl" t.string "smtp_server", :default => "localhost" t.integer "smtp_port", :default => 10025 t.string "currency_label", :limit => 15, :default => "$" t.float "bandwidth_cost", :default => 0.0, :null => false t.string "chart_ham_colour", :limit => 32, :default => "#DDDDB7" t.string "chart_spam_colour", :limit => 32, :default => "#FFAAAA" t.string "chart_virus_colour", :limit => 32, :default => "#CCFFCC" t.string "chart_fp_colour", :limit => 32, :default => "#C4CA73" t.string "chart_fn_colour", :limit => 32, :default => "#FF7575" t.string "chart_suspected_ham_colour", :limit => 32, :default => "#FFFFB7" t.string "chart_suspected_spam_colour", :limit => 32, :default => "#FFCCCC" t.string "chart_wl_colour", :limit => 32, :default => "#eeeeee" t.string "chart_bl_colour", :limit => 32, :default => "#888888" t.string "chart_background_colour", :limit => 32, :default => "#B0ECFF" t.string "chart_font_colour", :limit => 32, :default => "#3D3D50" t.integer "chart_autogeneration_interval", :default => 60 t.string "banner_title", :default => "Maia Mailguard" t.boolean "use_icons", :default => true, :null => false t.boolean "use_logo", :default => true, :null => false t.string "logo_url", :default => "http://www.maiamailguard.com/" t.string "logo_file", :default => "images/maia-logotoolbar.gif" t.string "logo_alt_text", :default => "Maia Mailguard Home Page" t.string "virus_info_url", :default => "http://www.google.com/search?q=%%VIRUSNAME%%+virus+information" t.string "virus_lookup", :limit => 20, :default => "google" t.string "primary_report_server", :default => "maia.renaissoft.com" t.integer "primary_report_port", :default => 443 t.string "secondary_report_server" t.integer "secondary_report_port", :default => 443 t.string "reporter_sitename" t.string "reporter_username", :limit => 50 t.string "reporter_password", :limit => 50 t.integer "size_limit", :default => 1000000 t.string "oversize_policy", :limit => 1, :default => "B", :null => false t.integer "sa_score_set", :default => 0, :null => false t.string "key_file", :default => "blowfish.key" end create_table "stats", :force => true do |t| t.integer "address_id", :null => false t.datetime "oldest_suspected_ham_date" t.datetime "newest_suspected_ham_date" t.integer "smallest_suspected_ham_size", :default => 0, :null => false t.integer "largest_suspected_ham_size", :default => 0, :null => false t.integer "total_suspected_ham_size", :limit => 8, :default => 0, :null => false t.float "lowest_suspected_ham_score", :default => 0.0, :null => false t.float "highest_suspected_ham_score", :default => 0.0, :null => false t.float "total_suspected_ham_score", :default => 0.0, :null => false t.integer "total_suspected_ham_items", :default => 0, :null => false t.datetime "oldest_ham_date" t.datetime "newest_ham_date" t.integer "smallest_ham_size", :default => 0, :null => false t.integer "largest_ham_size", :default => 0, :null => false t.integer "total_ham_size", :limit => 8, :default => 0, :null => false t.float "lowest_ham_score", :default => 0.0, :null => false t.float "highest_ham_score", :default => 0.0, :null => false t.float "total_ham_score", :default => 0.0, :null => false t.integer "total_ham_items", :default => 0, :null => false t.datetime "oldest_wl_date" t.datetime "newest_wl_date" t.integer "smallest_wl_size", :default => 0, :null => false t.integer "largest_wl_size", :default => 0, :null => false t.integer "total_wl_size", :limit => 8, :default => 0, :null => false t.integer "total_wl_items", :default => 0, :null => false t.datetime "oldest_bl_date" t.datetime "newest_bl_date" t.integer "smallest_bl_size", :default => 0, :null => false t.integer "largest_bl_size", :default => 0, :null => false t.integer "total_bl_size", :limit => 8, :default => 0, :null => false t.integer "total_bl_items", :default => 0, :null => false t.datetime "oldest_suspected_spam_date" t.datetime "newest_suspected_spam_date" t.integer "smallest_suspected_spam_size", :default => 0, :null => false t.integer "largest_suspected_spam_size", :default => 0, :null => false t.integer "total_suspected_spam_size", :limit => 8, :default => 0, :null => false t.float "lowest_suspected_spam_score", :default => 0.0, :null => false t.float "highest_suspected_spam_score", :default => 0.0, :null => false t.float "total_suspected_spam_score", :default => 0.0, :null => false t.integer "total_suspected_spam_items", :default => 0, :null => false t.datetime "oldest_fp_date" t.datetime "newest_fp_date" t.integer "smallest_fp_size", :default => 0, :null => false t.integer "largest_fp_size", :default => 0, :null => false t.integer "total_fp_size", :limit => 8, :default => 0, :null => false t.float "lowest_fp_score", :default => 0.0, :null => false t.float "highest_fp_score", :default => 0.0, :null => false t.float "total_fp_score", :default => 0.0, :null => false t.integer "total_fp_items", :default => 0, :null => false t.datetime "oldest_fn_date" t.datetime "newest_fn_date" t.integer "smallest_fn_size", :default => 0, :null => false t.integer "largest_fn_size", :default => 0, :null => false t.integer "total_fn_size", :limit => 8, :default => 0, :null => false t.float "lowest_fn_score", :default => 0.0, :null => false t.float "highest_fn_score", :default => 0.0, :null => false t.float "total_fn_score", :default => 0.0, :null => false t.integer "total_fn_items", :default => 0, :null => false t.datetime "oldest_spam_date" t.datetime "newest_spam_date" t.integer "smallest_spam_size", :default => 0, :null => false t.integer "largest_spam_size", :default => 0, :null => false t.integer "total_spam_size", :limit => 8, :default => 0, :null => false t.float "lowest_spam_score", :default => 0.0, :null => false t.float "highest_spam_score", :default => 0.0, :null => false t.float "total_spam_score", :default => 0.0, :null => false t.integer "total_spam_items", :default => 0, :null => false t.datetime "oldest_virus_date" t.datetime "newest_virus_date" t.integer "smallest_virus_size", :default => 0, :null => false t.integer "largest_virus_size", :default => 0, :null => false t.integer "total_virus_size", :limit => 8, :default => 0, :null => false t.integer "total_virus_items", :default => 0, :null => false t.datetime "oldest_bad_header_date" t.datetime "newest_bad_header_date" t.integer "smallest_bad_header_size", :default => 0, :null => false t.integer "largest_bad_header_size", :default => 0, :null => false t.integer "total_bad_header_size", :limit => 8, :default => 0, :null => false t.integer "total_bad_header_items", :default => 0, :null => false t.datetime "oldest_banned_file_date" t.datetime "newest_banned_file_date" t.integer "smallest_banned_file_size", :default => 0, :null => false t.integer "largest_banned_file_size", :default => 0, :null => false t.integer "total_banned_file_size", :limit => 8, :default => 0, :null => false t.integer "total_banned_file_items", :default => 0, :null => false t.datetime "oldest_oversized_date" t.datetime "newest_oversized_date" t.integer "smallest_oversized_size", :default => 0, :null => false t.integer "largest_oversized_size", :default => 0, :null => false t.integer "total_oversized_size", :limit => 8, :default => 0, :null => false t.integer "total_oversized_items", :default => 0, :null => false end add_index "stats", ["address_id"], :name => "stats_address_idx", :unique => true create_table "stats_snapshots", :force => true do |t| t.integer "address_id", :null => false t.string "stat_type", :limit => 1, :default => "H", :null => false t.datetime "taken_at", :null => false t.integer "total_ham_items", :default => 0, :null => false t.integer "total_ham_size", :limit => 8, :default => 0, :null => false t.integer "total_spam_items", :default => 0, :null => false t.integer "total_spam_size", :limit => 8, :default => 0, :null => false t.integer "total_virus_items", :default => 0, :null => false t.integer "total_virus_size", :limit => 8, :default => 0, :null => false t.integer "total_fp_items", :default => 0, :null => false t.integer "total_fp_size", :limit => 8, :default => 0, :null => false t.integer "total_fn_items", :default => 0, :null => false t.integer "total_fn_size", :limit => 8, :default => 0, :null => false t.integer "total_banned_file_items", :default => 0, :null => false t.integer "total_banned_file_size", :limit => 8, :default => 0, :null => false t.integer "total_bad_header_items", :default => 0, :null => false t.integer "total_bad_header_size", :limit => 8, :default => 0, :null => false t.integer "total_wl_items", :default => 0, :null => false t.integer "total_wl_size", :limit => 8, :default => 0, :null => false t.integer "total_bl_items", :default => 0, :null => false t.integer "total_bl_size", :limit => 8, :default => 0, :null => false t.integer "total_oversized_items", :default => 0, :null => false t.integer "total_oversized_size", :limit => 8, :default => 0, :null => false end add_index "stats_snapshots", ["address_id"], :name => "stats_snapshots_address_idx", :unique => true add_index "stats_snapshots", ["stat_type"], :name => "stats_snapshots_type_idx", :unique => true create_table "themes", :force => true do |t| t.string "name", :limit => 30, :null => false t.string "path", :limit => 30, :null => false end create_table "triggered_rules", :force => true do |t| t.integer "message_id", :null => false t.integer "rule_id", :null => false t.float "rule_score", :default => 0.0, :null => false end add_index "triggered_rules", ["message_id", "rule_id"], :name => "triggered_rules_idx", :unique => true create_table "tokens", :force => true do |t| t.string "token_system", :limit => 32, :null => false t.string "token", :limit => 64, :null => false t.binary "data", :null => false t.datetime "expires", :null => false end add_index "tokens", ["expires"], :name => "expires" add_index "tokens", ["token", "token_system"], :name => "token", :unique => true add_index "tokens", ["token_system"], :name => "token_system" create_table "users", :force => true do |t| t.string "login", :null => false t.string "user_level", :limit => 1, :default => "U", :null => false t.integer "primary_address_id", :default => 0, :null => false t.integer "language_id", :default => 1, :null => false t.integer "theme_id", :default => 1, :null => false t.boolean "reminders", :default => true, :null => false t.boolean "charts", :default => false, :null => false t.string "charset", :limit => 20, :default => "ISO-8859-1", :null => false t.boolean "spamtrap", :default => false, :null => false t.string "password", :limit => 32 t.boolean "auto_whitelist", :default => true, :null => false t.integer "items_per_page", :default => 50, :null => false t.string "spam_quarantine_sort", :limit => 2, :default => "XA", :null => false t.string "virus_quarantine_sort", :limit => 2, :default => "DA", :null => false t.string "header_quarantine_sort", :limit => 2, :default => "DA", :null => false t.string "attachment_quarantine_sort", :limit => 2, :default => "DA", :null => false t.string "ham_cache_sort", :limit => 2, :default => "XD", :null => false t.boolean "discard_ham", :default => false, :null => false t.integer "quarantine_digest_interval", :default => 0, :null => false t.datetime "last_digest_sent" t.integer "truncate_subject", :default => 20, :null => false t.integer "truncate_email", :default => 20, :null => false end add_index "users", ["theme_id"], :name => "users_theme_id_idx" add_index "users", ["login"], :name => "login_idx", :unique => true add_index "users", ["language_id"], :name => "users_language_idx" create_table "virus_aliases", :force => true do |t| t.integer "virus_id", :null => false t.string "virus_alias", :null => false end add_index "virus_aliases", ["virus_id", "virus_alias"], :name => "virus_alias_idx", :unique => true create_table "viruses", :force => true do |t| t.string "virus_name", :null => false t.integer "virus_count", :default => 0, :null => false end add_index "viruses", ["virus_name"], :name => "virus_name", :unique => true create_table "wblist_entries", :force => true do |t| t.integer "user_id", :null => false t.integer "sender_id", :null => false t.string "wb", :limit => 1, :null => false end add_index "wblist_entries", ["user_id", "sender_id"], :name => "sender_recipient", :unique => true end def self.down end end
module Jekyll module IntersectArrays def intersect(input, source) return [] unless input and source input & source end end end Liquid::Template.register_filter(Jekyll::IntersectArrays)
module ItemsHelper def time_from_today(the_time) seconds = (Time.now - the_time).to_i minutes = seconds / 60 hours = minutes / 60 days = hours / 24 months = days / 30 years = months / 12 if seconds < 60 result = seconds.to_s + ' seconds ago' elsif minutes < 60 result = minutes.to_s + ' minutes ago' elsif hours < 24 result = hours.to_s + ' hours ago' elsif days < 30 result = days.to_s + ' days ago' elsif months < 24 result = months.to_s + ' months ago' else result = years.to_s + ' years ago' end return result end end
if Rails.env.development? || Rails.env.test? begin require 'rubocop/rake_task' RuboCop::RakeTask.new(:rubocop) do |task| task.options = ['--display-cop-names'] end rescue LoadError warn 'rubocop is not available.' end begin require 'cane/rake_task' desc 'Run cane to check quality metrics' Cane::RakeTask.new(:cane) do |cane| cane.abc_max = 15 cane.no_style = true cane.abc_exclude = %w() cane.doc_exclude = ['**/*.rb'] end rescue LoadError warn 'cane is not available.' end desc 'Code quality' task quality: [:cane, :rubocop] end
class EndParticipantCallMutation < Types::BaseMutation description "End the participant's call leg" argument :participant_id, ID, required: true field :participant, Outputs::ParticipantType, null: true field :errors, resolver: Resolvers::Error policy CallPolicy, :manage? def resolve participant = Participant.active.find(input.participant_id) authorize participant.call result = EndParticipantCall.new(participant).call if result.success? {participant: result.participant, errors: []} else {participant: nil, errors: result.errors} end end end
ActiveAdmin.register Oscar do menu parent: "Pride",priority: 1 # See permitted parameters documentation: # https://github.com/activeadmin/activeadmin/blob/master/docs/2-resource-customization.md#setting-up-strong-parameters # permit_params :year, :best_picture_id, :best_supporting_actor_id, :best_supporting_actress_id, :best_actress_id, :best_actor_id, :best_adapted_screenplay_id,:best_original_screenplay_id, :best_director_id, :best_animated_feature_flim_id, :best_foreign_language_flim_id # # or # # permit_params do # permitted = [:permitted, :attributes] # permitted << :other if params[:action] == 'create' && current_user.admin? # permitted # end index do column :year actions end show do attributes_table do row :id row :best_picture do begin movie = Movie.find(oscar.best_picture_id) rescue movie = nil end link_to "#{movie.chinese_name}", admin_movie_path(id: oscar.best_picture.id) if movie.present? end row :best_director do begin director = Person.find(Director.find(oscar.best_director_id).person_id) rescue director = nil end link_to "#{director.chinese_name}", admin_director_path(id: oscar.best_director.id)if director.present? end row :best_actor do begin actor = Person.find(Actor.find(oscar.best_actor_id).person_id) rescue actor = nil end link_to "#{actor.chinese_name}", admin_actor_path(id: oscar.best_actor.id)if actor.present? end row :best_actress do begin actor = Person.find(Actor.find(oscar.best_actress_id).person_id) rescue actor = nil end link_to "#{actor.chinese_name}", admin_actor_path(id: oscar.best_actress.id)if actor.present? end row :best_supporting_actor do begin actor = Person.find(Actor.find(oscar.best_supporting_actor_id).person_id) rescue actor = nil end link_to "#{actor.chinese_name}", admin_actor_path(id: oscar.best_supporting_actor.id)if actor.present? end row :best_supporting_actress do begin actor = Person.find(Actor.find(oscar.best_supporting_actress_id).person_id) rescue actor = nil end link_to "#{actor.chinese_name}", admin_actor_path(id: oscar.best_supporting_actress.id)if actor.present? end row :best_animated_feature_flim do begin movie = Movie.find(oscar.best_animated_feature_flim_id) rescue movie = nil end link_to "#{movie.chinese_name}", admin_movie_path(id: oscar.best_animated_feature_flim.id)if movie.present? end row :best_foreign_language_flim do begin movie = Movie.find(oscar.best_animated_feature_flim_id) rescue movie = nil end link_to "#{movie.chinese_name}", admin_movie_path(id: oscar.best_animated_feature_flim.id)if movie.present? end row :best_original_screenplay do begin movie = Movie.find(Writer.find(oscar.best_original_screenplay_id).movie_id) rescue movie = nil end link_to "#{movie.chinese_name}", admin_writer_path(id: oscar.best_original_screenplay.id)if movie.present? end row :best_adapted_screenplay do begin movie = Movie.find(Writer.find(oscar.best_adapted_screenplay_id).movie_id) rescue movie = nil end link_to "#{movie.chinese_name}", admin_writer_path(id: oscar.best_adapted_screenplay.id)if movie.present? end end end form do |f| f.actions f.inputs do f.input :year f.input :best_picture_id, as: :select, :collection => Movie.all.map{|m| ["#{m.chinese_name}", m.id]} f.input :best_director_id, as: :select, :collection => Director.all.map{|d| ["#{Person.find(d.person_id).chinese_name}/#{Movie.find(d.movie_id).chinese_name}", d.id]} f.input :best_actor_id, as: :select, :collection => Actor.all.map{|a| ["#{Person.find(a.person_id).chinese_name}/#{Movie.find(a.movie_id).chinese_name}", a.id]} f.input :best_actress_id, as: :select, :collection => Actor.all.map{|a| ["#{Person.find(a.person_id).chinese_name}/#{Movie.find(a.movie_id).chinese_name}", a.id]} f.input :best_supporting_actor_id, as: :select, :collection => Actor.all.map{|a| ["#{Person.find(a.person_id).chinese_name}/#{Movie.find(a.movie_id).chinese_name}", a.id]} f.input :best_supporting_actress_id, as: :select, :collection => Actor.all.map{|a| ["#{Person.find(a.person_id).chinese_name}/#{Movie.find(a.movie_id).chinese_name}", a.id]} f.input :best_animated_feature_flim_id, as: :select, :collection => Movie.all.map{|m| ["#{m.chinese_name}", m.id]} f.input :best_foreign_language_flim_id, as: :select, :collection => Movie.all.map{|m| ["#{m.chinese_name}", m.id]} f.input :best_original_screenplay_id, as: :select, :collection => Writer.all.map{|w| ["#{Person.find(w.person_id).chinese_name}/#{Movie.find(w.movie_id).chinese_name}", w.id]} f.input :best_adapted_screenplay_id, as: :select, :collection => Writer.all.map{|w| ["#{Person.find(w.person_id).chinese_name}/#{Movie.find(w.movie_id).chinese_name}", w.id]} end f.actions end config.filters = false end
require 'rails_helper' feature 'Only author can delete the question', %q{ In order to cancel requests to community for help As an author of the question I'd like to be able to delete the question } do given(:question) { create(:question, title: 'test_delete_question', body: '12345') } describe 'An authenticated user' do given(:user) { create(:user) } scenario 'deletes his question' do sign_in(question.author) visit question_path(question) click_on 'Delete question' expect(page).to_not have_content 'test_delete_question' end scenario 'tries to delete a question of another user' do sign_in(user) visit question_path(question) expect(page).to_not have_link 'Delete question' end end scenario 'An unauthenticated user tries to delete any question' do visit question_path(question) expect(page).to_not have_link 'Delete question' end end
# Object to save user password as session variable class CreateAppPayload include ModelHelper def initialize(email, password, tsalt) @email = email @password = password @tsalt = tsalt end def call payload = base_64_encode( Teacher.token_key(@password, base_64_decode(@tsalt)) ) TokenSetPayload.new(@email, payload).payload end end
require 'crossed_wires/wire' require 'crossed_wires/point' RSpec.describe CrossedWires::Wire do subject(:wire) { described_class.new(points) } let(:points_alfa) do [ CrossedWires::Point.new(0, 0), CrossedWires::Point.new(0, 5), CrossedWires::Point.new(4, 5), CrossedWires::Point.new(4, -5), CrossedWires::Point.new(-6, -5) ] end let(:points_bravo) do [ CrossedWires::Point.new(0, 0), CrossedWires::Point.new(-4, 0), CrossedWires::Point.new(-4, -5), CrossedWires::Point.new(6, -5), CrossedWires::Point.new(6, 5) ] end describe '#horizontal_sections' do subject(:horizontal_sections) { wire.horizontal_sections } context 'case 1' do let(:points) { points_alfa } it 'returns horizontal parts of wire' do expect(horizontal_sections).to contain_exactly( have_attributes(begining: have_attributes(x: 0, y: 5), ending: have_attributes(x: 4, y: 5)), have_attributes(begining: have_attributes(x: 4, y: -5), ending: have_attributes(x: -6, y: -5)) ) end end context 'case 2' do let(:points) { points_bravo } it 'returns sorted horizontal parts of wire' do expect(horizontal_sections).to contain_exactly( have_attributes(begining: have_attributes(x: 0, y: 0), ending: have_attributes(x: -4, y: 0)), have_attributes(begining: have_attributes(x: -4, y: -5), ending: have_attributes(x: 6, y: -5)) ) end end end describe '#vertical_sections' do subject(:vertical_sections) { wire.vertical_sections } context 'wire alfa' do let(:points) { points_alfa } it 'returns sorted vertical parts of wire' do expect(vertical_sections).to contain_exactly( have_attributes(begining: have_attributes(x: 0, y: 0), ending: have_attributes(x: 0, y: 5)), have_attributes(begining: have_attributes(x: 4, y: 5), ending: have_attributes(x: 4, y: -5)) ) end end context 'wire bravo' do let(:points) { points_bravo } it 'returns vertical parts of wire' do expect(vertical_sections).to contain_exactly( have_attributes(begining: have_attributes(x: -4, y: 0), ending: have_attributes(x: -4, y: -5)), have_attributes(begining: have_attributes(x: 6, y: -5), ending: have_attributes(x: 6, y: 5)) ) end end end describe '#steps_to' do subject(:steps_to) { wire.steps_to(point) } context 'wire alfa' do let(:points) { points_alfa } context 'with point {0,5}' do let(:point) { CrossedWires::Point.new(0, 5) } it { is_expected.to eq(5) } end context 'with point {0,2}' do let(:point) { CrossedWires::Point.new(0, 2) } it { is_expected.to eq(2) } end context 'with point {2,5}' do let(:point) { CrossedWires::Point.new(2, 5) } it { is_expected.to eq(7) } end end end end
# -*- encoding : utf-8 -*- module Retailigence #:nodoc: # Representation of the distance from the <tt>userlocation</tt> and the # respective Product or Location # # === Attributes # * <tt>distance</tt> - A float value based on the distance <tt>units</tt> # * <tt>units</tt> - String of distance measurement. Example: "miles", "meters", etc. class Distance < Model attributes :distance, :units end end
# frozen_string_literal: true Given("the Formicidae family exists") do create :family, name_string: "Formicidae" end
class Greeter def initialize (name = "World") @name = name end def say_hi puts "Hello #{@name}" end def say_goodbye puts "See ya later #{@name}!" end def quick puts @name[0..2] end end
module Admin class ImageGalleryImagesController < ApplicationController # GET /image_gallery_images # GET /image_gallery_images.xml before_filter :load_image_gallery_group def load_image_gallery_group @image_gallery_group = ImageGalleryGroup.find(params[:image_gallery_group_id]) end # GET /image_gallery_images/new # GET /image_gallery_images/new.xml def new @image_gallery_image = @image_gallery_group.images.new respond_to do |format| format.html # new.html.erb format.xml { render :xml => @image_gallery_image } end end # GET /image_gallery_images/1/edit def edit @image_gallery_image = @image_gallery_group.images.find(params[:id]) end # POST /image_gallery_images # POST /image_gallery_images.xml def create @image_gallery_image = @image_gallery_group.images.new(params[:image_gallery_image]) respond_to do |format| if @image_gallery_image.save flash[:notice] = 'ImageGalleryImage was successfully created.' format.html { redirect_to([:admin, @image_gallery_group]) } format.xml { render :xml => @image_gallery_group, :status => :created, :location => @image_gallery_group } else format.html { render :action => "new" } format.xml { render :xml => @image_gallery_group.errors, :status => :unprocessable_entity } end end end # PUT /image_gallery_images/1 # PUT /image_gallery_images/1.xml def update @image_gallery_image = ImageGalleryImage.find(params[:id]) respond_to do |format| if @image_gallery_image.update_attributes(params[:image_gallery_image]) flash[:notice] = 'ImageGalleryImage was successfully updated.' format.html { redirect_to([:admin, @image_gallery_group]) } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @image_gallery_image.errors, :status => :unprocessable_entity } end end end # DELETE /image_gallery_images/1 # DELETE /image_gallery_images/1.xml def destroy @image_gallery_image = ImageGalleryImage.find(params[:id]) @image_gallery_image.destroy respond_to do |format| format.html { redirect_to([:admin, @image_gallery_group]) } format.xml { head :ok } end end end end
class PlayersController < ApplicationController before_action :set_player, only: [:show, :edit, :update, :destroy] before_action :rand_logic, only: :index require 'Logica' # GET /players # GET /players.json def index @m = Logica.start_engine @players = Player.all if @players.count > 0 @players.each do |p| @rand_u = @probabilities[rand(0..99)] if @rand_u == @rand_pr p.update(money:1000) @winners << p else p.update(money:0) @losers << p end end end end # GET /players/1 # GET /players/1.json def show end # GET /players/new def new @player = Player.new end # GET /players/1/edit def edit end # POST /players # POST /players.json def create @player = Player.new(player_params) respond_to do |format| if @player.save format.html { redirect_to @player, notice: 'Player was successfully created.' } format.json { render action: 'show', status: :created, location: @player } else format.html { render action: 'new' } format.json { render json: @player.errors, status: :unprocessable_entity } end end end # PATCH/PUT /players/1 # PATCH/PUT /players/1.json def update respond_to do |format| if @player.update(player_params) format.html { redirect_to @player, notice: 'Player was successfully updated.' } format.json { head :no_content } else format.html { render action: 'edit' } format.json { render json: @player.errors, status: :unprocessable_entity } end end end # DELETE /players/1 # DELETE /players/1.json def destroy @player.destroy respond_to do |format| format.html { redirect_to players_url } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_player @player = Player.find(params[:id]) end def rand_logic @roulette = ["Rojo", "Negro", "Verde"] @probabilities = [] @winners = [] @losers = [] (0..99).each do |r| if r <= 47 @probabilities << @roulette[0] elsif r > 47 && r <=97 @probabilities << @roulette[1] else @probabilities << @roulette[2] end end @rand_pr = @probabilities[rand(0..99)] end # Never trust parameters from the scary internet, only allow the white list through. def player_params params.require(:player).permit(:name, :last_name, :age, :money) end end
Spree::Api::BaseController.class_eval do skip_before_filter :authenticate_user, if: :create_user_action? def create_user_action? req = request.path_parameters req[:controller] === 'spree/api/users' && req[:action] == 'create' end end
class RMQViewStyler attr_accessor :view attr_accessor :context attr_accessor :bg_color attr_accessor :corner_radius def initialize(view, context) @needs_finalize = false @view = view @context = context @bg_color = nil @corner_radius = nil end def cleanup @layout_params = nil @needs_finalize = nil @context = nil @bg_color = nil @corner_radius = nil @margin = nil @padding = nil @view = nil end def convert_dimension_value(value) case value when :match_parent, :full Android::View::ViewGroup::LayoutParams::MATCH_PARENT when :wrap_content Android::View::ViewGroup::LayoutParams::WRAP_CONTENT else dp2px(value) end end def layout_params @layout_params ||= begin #@view.setMargins(0, 0, 0, 0) #mp @view.LayoutParams if lp = @view.getLayoutParams lp else #mp 1 #mp @view Android::View::ViewGroup::LayoutParams.new(0,0) #Android::Widget::LinearLayout::LayoutParams.new(0,0) end end end def layout=(value) return unless lp = layout_params if value == :full lp.width = convert_dimension_value(:full) lp.height = convert_dimension_value(:full) @view.setLayoutParams(lp) elsif value.is_a?(Hash) hash = value if w = (hash[:w] || hash[:width]) lp.width = convert_dimension_value(w) end if h = (hash[:h] || hash[:height]) lp.height = convert_dimension_value(h) end if l = (hash[:l] || hash[:left] || hash[:left_margin]) lp.leftMargin = convert_dimension_value(l) end if t = (hash[:t] || hash[:top] || hash[:top_margin]) lp.topMargin = convert_dimension_value(t) end if fr = (hash[:fr] || hash[:from_right] || hash[:right_margin]) lp.rightMargin = convert_dimension_value(fr) end if fb = (hash[:fb] || hash[:from_bottom] || hash[:bottom_margin]) lp.bottomMargin = convert_dimension_value(fb) end # TODO do center # TODO gravity # TODO do the relative bits @view.setLayoutParams(lp) if pad = hash[:padding] self.padding = pad end end end alias :frame= :layout= def padding=(pad) if pad.is_a?(Potion::Integer) pad = convert_dimension_value(pad) @view.setPadding(pad, pad, pad, pad) elsif pad.is_a?(Hash) @view.setPadding( convert_dimension_value(pad[:l] || pad[:left] || 0), convert_dimension_value(pad[:t] || pad[:top] || 0), convert_dimension_value(pad[:r] || pad[:right] || 0), convert_dimension_value(pad[:b] || pad[:bottom] || 0)) else mp pad.class.name end end # use this if you need to do something after all style methods have been called (e.g. # applying layout params) def finalize return unless @needs_finalize create_rounded_bg if corner_radius layout_params.setMargins(margin[:left], margin[:top], margin[:right], margin[:bottom]) if layout_params.respond_to?(:setMargins) @view.setLayoutParams(layout_params) @view.setPadding(padding[:left], padding[:top], padding[:right], padding[:bottom]) end def background_color=(color) @view.backgroundColor = @bg_color = convert_color(color) end def background_resource=(bg) @view.backgroundResource = bg end def layout_width=(layout_width) @needs_finalize = true layout_params.width = convert_dimension_value(layout_width) end def layout_height=(layout_height) @needs_finalize = true layout_params.height = convert_dimension_value(layout_height) end def gravity=(gravity) layout_params.gravity = convert_gravity(gravity) end def layout_center_in_parent=(center_in_parent) @needs_finalize = true center = center_in_parent ? Android::Widget::RelativeLayout::TRUE : Android::Widget::RelativeLayout::FALSE layout_params.addRule(Android::Widget::RelativeLayout::CENTER_IN_PARENT, center) end def layout_center_vertical=(center_vertical) @needs_finalize = true center = center_vertical ? Android::Widget::RelativeLayout::TRUE : Android::Widget::RelativeLayout::FALSE layout_params.addRule(Android::Widget::RelativeLayout::CENTER_VERTICAL, center) end def layout_center_horizontal=(center_horizontal) @needs_finalize = true center = center_horizontal ? Android::Widget::RelativeLayout::TRUE : Android::Widget::RelativeLayout::FALSE layout_params.addRule(Android::Widget::RelativeLayout::CENTER_HORIZONTAL, center) end def layout_align_parent_left=(left_in_parent) @needs_finalize = true left = left_in_parent ? Android::Widget::RelativeLayout::TRUE : Android::Widget::RelativeLayout::FALSE layout_params.addRule(Android::Widget::RelativeLayout::ALIGN_PARENT_LEFT, left) end def layout_align_parent_right=(right_in_parent) @needs_finalize = true right = right_in_parent ? Android::Widget::RelativeLayout::TRUE : Android::Widget::RelativeLayout::FALSE layout_params.addRule(Android::Widget::RelativeLayout::ALIGN_PARENT_RIGHT, right) end def padding_left=(pad_left) @needs_finalize = true padding[:left] = dp2px(pad_left) end def padding_top=(pad_top) @needs_finalize = true padding[:top] = dp2px(pad_top) end def padding_right=(pad_right) @needs_finalize = true padding[:right] = dp2px(pad_right) end def padding_bottom=(pad_bottom) @needs_finalize = true padding[:bottom] = dp2px(pad_bottom) end def margin_left=(m_left) @needs_finalize = true margin[:left] = dp2px(m_left) end def margin_top=(m_top) @needs_finalize = true margin[:top] = dp2px(m_top) end def margin_right=(m_right) @needs_finalize = true margin[:right] = dp2px(m_right) end def margin_bottom=(m_bottom) @needs_finalize = true margin[:bottom] = dp2px(m_bottom) end def margin=(m) @needs_finalize = true margin[:left] = margin[:top] = margin[:right] = margin[:bottom] = dp2px(m) end # This can only be used on a widget that's within a LinearLayout def layout_weight=(weight) @needs_finalize = true layout_params.weight = weight end def layout_gravity=(gravity) @needs_finalize = true layout_params.gravity = convert_gravity(gravity) end def corner_radius(corner_radius) @needs_finalize = true @corner_radius = dp2px(corner_radius) end def convert_color(color) return ColorFactory.from_hex(color) if color.is_a?(String) color end def convert_gravity(gravity) case gravity when :center then Android::View::Gravity::CENTER when :left then Android::View::Gravity::LEFT else gravity end end def dp2px(dp_val) (dp_val * density + 0.5).to_i end def density @density ||= @context.getResources.getDisplayMetrics.density end def create_drawable(corner_radius) createDrawable(corner_radius) end def visibility=(value) case value when :visible, true view.setVisibility(Potion::View::VISIBLE) when :invisible, false view.setVisibility(Potion::View::INVISIBLE) when :gone view.setVisibility(Potion::View::GONE) end end alias :visible= :visibility= private def padding @padding ||= { left: 0, top: 0, right: 0, bottom: 0 } end def margin @margin ||= { left: 0, top: 0, right: 0, bottom: 0 } end def convert_dimension_value(value) case value when :match_parent, :full Android::View::ViewGroup::LayoutParams::MATCH_PARENT when :wrap_content Android::View::ViewGroup::LayoutParams::WRAP_CONTENT else dp2px(value) end end def create_rounded_bg # creating this shape in Ruby raises an ART error, but it works in Java #radii = [corner_radius, corner_radius, corner_radius, corner_radius, # corner_radius, corner_radius, corner_radius, corner_radius] #shape = Android::Graphics::Drawable::Shapes::RoundRectShape.new(radii, nil, nil) # StyleHelper contains a Java extension shape = StylerHelper.shared.createRoundRect(dp2px(corner_radius)) drawable = Android::Graphics::Drawable::ShapeDrawable.new(shape) drawable.paint.color = bg_color @view.setBackgroundDrawable(drawable) end end
module V1 class SessionAPI < Grape::API resource :session do post :login do user = User.find_for_authentication(email: params[:email]) raise V1::Exceptions::Unauthorized unless user.valid_password?(params[:password]) { token: user.generate_token, user: user } end end end end
class WeWorkRemotely < CrawlBase def self.config { url: "https://weworkremotely.com/jobs/search?term=rails", base_url: "https://weworkremotely.com", list_link_selector: "article li a", }.freeze end def to_h { company_name: doc.css(".listing-header-container .company").first.try(:text), title: doc.css(".listing-header-container h1").first.try(:text), company_url: doc.css(".listing-header-container h2 a").first.try(:text), how_to_apply: doc.css(".apply p").first.try(:text), description: ReverseMarkdown.convert(doc.css(".job .listing-container").first.try(:to_html)).to_s.strip } end end
RSpec.describe Entry, type: :model do let(:entry) { Entry.find('1') } describe '#first_part' do it { expect(entry.first_part).to eq('aaa') } end describe '#theme' do it { expect(entry.theme).to eq('default_2008 article') } end describe '#og_description' do context :entry_1 do let(:entry) { Entry.find('1022457036') } let(:expected) do ' img.response {width: 400px;}span.res_user {color: rgb(0, 128, 0);}' \ 'span.res_user {color: rgb(0, 128, 0);}乃木坂46人気がヤバイwwwww' \ 'wwwwwwwww 1: 名無し募集中。。。@' \ '\(^o^)/: 2015/03/22(日)' end it { expect(entry.og_description).to eq(expected) } end context :entry_2 do let(:entry) { Entry.find('1022455973') } let(:expected) do ' img.response {width: 400px;}span.res_user {color: rgb(0, 128, 0);}' \ 'span.res_user {color: rgb(0, 128, 0);}【芸能】広瀬すずのゴリ押し戦略 ' \ 'ドラマ不調で「時期尚早」との見方も ' \ '1: coffeemilk ★@\(^o^)/: 20' end it { expect(entry.og_description).to eq(expected) } end end describe '#next' do let(:entry_1) { Entry.find('1022457036') } let(:entry_2) { Entry.find('1022455973') } it { expect(entry_2.next).to eq(entry_1) } end describe '#prev' do let(:entry_1) { Entry.find('1022457036') } let(:entry_2) { Entry.find('1022455973') } it { expect(entry_1.prev).to eq(entry_2) } end end RSpec.describe TopEntry, type: :model do describe '#five_numbers' do context 'given page: 2' do let(:entry) { TopEntry.new(page: 2) } it do allow(entry).to receive(:all_pages_size).and_return(10) expect(entry.five_numbers).to eq([1, 2, 3, 4, 5]) end end context 'given page: 9' do let(:entry) { TopEntry.new(page: 9) } it do allow(entry).to receive(:all_pages_size).and_return(10) expect(entry.five_numbers).to eq([6, 7, 8, 9, 10]) end end context 'given page: 6' do let(:entry) { TopEntry.new(page: 6) } it do allow(entry).to receive(:all_pages_size).and_return(10) expect(entry.five_numbers).to eq([4, 5, 6, 7, 8]) end end end end
module Forums class PostPresenter < BasePresenter presents :post def created_by @created_by ||= present(post.created_by) end def thread @thread ||= present(post.thread) end def created_at post.created_at.strftime('%c') end def created_at_in_words time_ago_in_words post.created_at end def last_edited post.updated_at.strftime('%c') end def last_edited_in_words time_ago_in_words post.updated_at end def content # rubocop:disable Rails/OutputSafety post.content_render_cache.html_safe # rubocop:enable Rails/OutputSafety end def quote header = "> **#{post.created_by.name}**" text = post.content.split("\n").map { |line| "> #{line}" }.join("\n") [header, text].join("\n") end def edit_path if post.first_post? edit_forums_thread_path(post.thread) else edit_forums_post_path(post) end end end end
class ClientsController < ApplicationController def index setup_session_defaults_for_controller(:client, :last_name) @clients = build_query(Client, :client) end def new unless company = Company.find_by_id(params[:company_id]) flash[:error] = 'You must supply a company to create a client for.' redirect_to companies_path return end unless current_user.admin? or current_user.all_properties.include? company.property flash[:error] = 'You do not have permission to create clients for that company.' redirect_to clients_path return end @client = Client.create(:company_id => company.id, :property_id => company.property_id) redirect_to edit_client_path(@client) end def edit unless @client = Client.find_by_id(params[:id]) flash[:error] = 'I could not find a client with that ID.' redirect_to clients_path end end def update unless @client = Client.find_by_id(params[:id]) flash[:error] = 'I could not find a client with that ID.' redirect_to clients_path end if @client.update_attributes(params[:client]) flash[:notice] = 'Client updated.' redirect_to @client else flash[:error] = 'There was a problem updating the client.' redirect_to edit_client_path(@client) end end def show unless @client = Client.find_by_id(params[:id]) flash[:error] = 'I could not find a client with that ID.' redirect_to clients_path end end def destroy unless @client = Client.find_by_id(params[:id]) flash[:error] = 'I could not find a client with that ID.' else flash[:notice] = "Client #{@client} destroyed." @client.destroy end redirect_to clients_path end end
class CreateMeals < ActiveRecord::Migration[5.0] def change create_table :meals do |t| t.string :main_title t.string :sub_title t.string :description t.string :cook_time t.integer :servings_count #remove t.integer :calories_count t.date :expected_date t.belongs_to :provider t.string :hero_image t.timestamps end end end
atom_feed :url => forum_topic_url(@forum, @topic) do |feed| feed.title(@topic) feed.updated(@posts.first ? @posts.first.created_at : Time.now.utc) @posts.each do |post| feed.entry post, :url => forum_topic_url(@forum, @topic, :page => post.page) do |entry| entry.title(@topic) entry.content(format_text(post.body), :type => 'html') entry.author do |author| author.name(post.user) end end end end
class AddInstagramPicToPosts < ActiveRecord::Migration def change add_column :posts, :instagram_pic, :string end end