text
stringlengths
10
2.61M
module Yt module Models # @private class URL attr_reader :kind def initialize(url) @url = url @kind ||= parse url @match_data ||= {} end def id @match_data[:id] rescue IndexError end def username @match_data[:username] rescue IndexError end private def parse(url) matching_pattern = patterns.find do |pattern| @match_data = url.match pattern[:regex] end matching_pattern[:kind] if matching_pattern end def patterns # @note: :channel *must* be the last since one of its regex eats the # remaining patterns. In short, don't change the following order @patterns ||= patterns_for :playlist, :subscription, :video, :channel end def patterns_for(*kinds) prefix = '^(?:https?://)?(?:www\.)?' suffix = '(?:|/)' kinds.map do |kind| patterns = send "#{kind}_patterns" # meta programming :/ patterns.map do |pattern| {kind: kind, regex: %r{#{prefix}#{pattern}#{suffix}}} end end.flatten end def subscription_patterns name = '(?:[a-zA-Z0-9&_=-]*)' %W{ subscription_center\\?add_user=#{name} subscribe_widget\\?p=#{name} channel/#{name}\\?sub_confirmation=1 }.map{|path| "youtube\\.com/#{path}"} end def playlist_patterns playlist_id = '(?<id>[a-zA-Z0-9_-]+)' %W{ playlist\\?list=#{playlist_id} }.map{|path| "youtube\\.com/#{path}"} end def video_patterns video_id = '(?<id>[a-zA-Z0-9_-]+)' %W{ youtube\\.com/watch\\?v=#{video_id} youtu\\.be/#{video_id} youtube\\.com/embed/#{video_id} youtube\\.com/v/#{video_id} } end def channel_patterns channel_id = '(?<id>[a-zA-Z0-9_-]+)' username = '(?<username>[a-zA-Z0-9_-]+)' %W{ channel/#{channel_id} user/#{username} #{username} }.map{|path| "youtube\\.com/#{path}"} end end end end
class TaskListController < ApplicationController before do render_unauthorized if auth_header_token.nil? auth_response_dto = AuthServiceHelper.find_user_by_token(auth_header_token) return render_response(auth_response_dto) if auth_response_dto.error? @user_id = auth_response_dto.data['userId'] end post '/task_lists' do response_dto = CoreServiceHelper.create_task_list(create_params.to_json) render_response(response_dto) end get '/task_lists' do response_dto = CoreServiceHelper.get_task_lists(index_params.to_json) render_response(response_dto) end private def index_params { user_id: @user_id } end def create_params { user_id: @user_id, name: body_params['name'], description: body_params['description'], frequence_type: body_params['frequenceType'] } end end
require 'spec_helper' describe Review do it { should belong_to(:user) } it { should belong_to(:video) } it { should validate_presence_of(:video) } it { should validate_presence_of(:user) } it { should validate_presence_of(:rating) } it { should validate_presence_of(:content) } it "does not allow two reviews by the same user for the same video" do video = Fabricate(:video) user = Fabricate(:user) Review.create(rating: 2, content: 'skip', video: video, user: user) second_review = Review.new(rating: 5, content: 'the best', video: video, user: user) expect(second_review.save).to_not be(true) end end
module AdminArea class BanksController < AdminController def index render cell(Banks::Cell::Index, Bank.alphabetical) end end end
class ModsToughness < ActiveRecord:: has_one :mod_secondary, as: :mods end
class ModuleInstancesController < ApplicationController # GET /module_instances # GET /module_instances.json def index # We are actually looking for the template return if redirect?( nil ) @filters = { } @filters[:cell] = params[:cell].to_i if params.has_key?(:cell) @filters[:template] = params[:template].to_i if params.has_key?(:template) #get_filters( :cell, :template ) @module_instances = ModuleInstance.paginate( :page => params[:page], :per_page => 15 ) @module_instances = filter_on_key( @module_instances, :module_template_id, @filters[:template] ) if ( !@filters[:template].nil? ) @module_instances = filter_on_key( @module_instances, :cell_id, @filters[:cell] ) if ( !@filters[:cell].nil? ) respond_to do |format| format.html # index.html.erb format.json { render json: @module_instances } end end # GET /module_instances/1 # GET /module_instances/1.json def show # We need the following data # # Instance < Template # Template has Parameters # Instance has Values # @module_instance = ModuleInstance.find( params[:id] ) @cell = @module_instance.cell @module_template = @module_instance.module_template return if redirect?( @module_template ) # Gets the parameters and values and hashes them. Missing # values are substituted with nils, so the parameters will # show up. @module_parameters = @module_instance.module_parameters @module_values = @module_instance.module_values @module_hash = Hash[ ( @module_parameters.map { |p| p.key } ).zip( @module_parameters.map { |p| ( found = ( @module_values.select{ |v| v.module_parameter == p } ).first ).nil? ? nil : ( found.value.nil? or found.value.empty? ? "[]" : JSON.parse( found.value )[0] ) } ) ] respond_to do |format| format.html # show.html.erb if ( params.has_key?(:all) ) @module_hash[:id] = @module_instance.id format.json { render json: { id: @module_instance.id, cell_id: @module_instance.cell_id, type: @module_template.javascript_model, step: @module_template.step, name: @module_instance.name, amount: @module_instance.amount, parameters: @module_hash } } else format.json { render json: @module_instance } end end end # GET /module_instances/new # GET /module_instances/new.json def new @module_instance = ModuleInstance.new @module_instance.build_cell @module_instance.build_module_template @module_instance.module_values.build @module_instance.module_parameters.build respond_to do |format| format.html # new.html.erb format.json { render json: @module_instance } end end # GET /module_instances/1/edit def edit @module_instance = ModuleInstance.find(params[:id]) @module_parameters = @module_instance.module_parameters @module_values = @module_instance.module_values @module_hash = Hash[ ( @module_parameters.map { |p| p.key } ).zip( @module_parameters.map { |p| ( found = ( @module_values.select{ |v| v.module_parameter == p } ).first ).nil? ? nil : ( found.value.nil? or found.value.empty? ? "[]" : JSON.parse( found.value )[0] ) } ) ] end # POST /module_instances # POST /module_instances.json def create @module_instance = ModuleInstance.new(params[:module_instance]) respond_to do |format| if @module_instance.save format.html { redirect_to @module_instance, notice: 'Module instance was successfully created.' } format.json { render json: @module_instance, status: :created, location: @module_instance } else format.html { render action: "new" } format.json { render json: @module_instance.errors, status: :unprocessable_entity } end end end # PUT /module_instances/1 # PUT /module_instances/1.json def update @module_instance = ModuleInstance.find(params[:id]) respond_to do |format| if params.has_key?( :module_parameters ) parameter_update( params[:module_parameters] ) end if @module_instance.update_attributes(params[:module_instance]) format.html { redirect_to @module_instance, notice: 'Module instance was successfully updated.' } format.json { render json: @module_instance } else format.html { render action: "edit" } format.json { render json: @module_instance.errors, status: :unprocessable_entity } end end end # DELETE /module_instances/1 # DELETE /module_instances/1.json def destroy @module_instance = ModuleInstance.find(params[:id]) @module_instance.destroy respond_to do |format| format.html { redirect_to module_instances_url } format.json { head :no_content } end end private # GET /module_instances.json?redirect=template # GET /module_instances/1.json?redirect=template def redirect?( module_template ) if params[:redirect] == 'template' # This is an existing instance if ( module_template ) respond_to do |format| format.json { redirect_to module_template_path( module_template, :format => 'json' ), :status => :found } end return true # This is a new instance (maybe existing template) else type = params.has_key?(:type) ? params[:type] : '' module_template = ModuleTemplate.where( :javascript_model => type ).first respond_to do |format| if ( module_template ) format.json { redirect_to module_template_path( module_template, :format => 'json' ), :status => :found } else format.json { head :no_content } end end return true end end return false end # Tries to update the parameters # def parameter_update( parameters ) @module_instance.module_parameters .each do |p| updated_parameter = nil parameters.each do |i,u| updated_parameter = u if u[:key] == p.key if u.nil? or updated_parameter.nil? or not updated_parameter[:value] updated_parameter = { :value => [] } end end if ( !updated_parameter.nil? ) current_parameter = ( @module_instance.module_values.select{ |v| v.module_parameter == p } ).first if ( current_parameter.nil? ) value = ModuleValue.create( { module_instance_id: @module_instance.id, module_parameter_id: p.id, value: [updated_parameter[:value]].to_json }) value.save else current_parameter.update_attributes( { value: [updated_parameter[:value]].to_json } ) end end end end end
require 'tempfile' module Tins module TempIO def temp_io(content = nil) Tempfile.open(__method__.to_s, binmode: true) do |io| if content.respond_to?(:call) content = content.call end io.write content io.rewind yield io end end end end
class GuildPanel::InvitesController < ApplicationController before_action :authenticate_user! layout 'guild_panel' before_action :load_guild, only: [:index] before_action :load_invites, only: [:index] before_action :load_invite, only: [:approval, :accepted, :reject] def index end def approval @invite.approval redirect_to :back end def accepted @invite.accepted @invite.character.enroll_in_guild(@invite) redirect_to :back end def reject @invite.reject redirect_to :back end private def load_guild @guild = Guild.find(params[:guild_id]) end def load_invites @invites = @guild.invites end def load_invite @invite = Invite.find(params[:id]) end end
require File.join( File.dirname( __FILE__ ), "..", "spec_helper" ) describe SSH::ShProcess do it "should keep output log" do shell = mock( "shell" ).as_null_object shell.stub( :on_stdout ).and_yield( "stdout" ) shell.stub( :on_stderr ).and_yield( "stderr" ) SubProcess.stub( :create ).and_yield( shell ) ssh = SSH.new ssh.sh( "yutaro00", "echo 'hello world'" ) ssh.output.should == <<-EOF stdout stderr EOF end end ### Local variables: ### mode: Ruby ### coding: utf-8-unix ### indent-tabs-mode: nil ### End:
class AddIncentiveToReservations < ActiveRecord::Migration def change add_reference :reservations, :incentive, index: true add_foreign_key :reservations, :incentives end end
class AddOrdenToPia < ActiveRecord::Migration def change add_column :pia, :orden, :integer end end
class Misc::PearlsController < Misc::BaseController before_filter :no_header def create @pearl = Pearl.new pearl_params create! do |success, failure| success.html { redirect_to misc_pearl_path(resource) } failure.html { render :new } end end private def pearl_params params.require(:pearl).permit! end end
# == Schema Information # Schema version: 20110429131040 # # Table name: notes # # id :integer not null, primary key # header :string(255) # body :text # position_x :integer # position_y :integer # owner_id :integer # created_at :datetime # updated_at :datetime # field_id :integer # trashcan :boolean # color :string(255) # class Note < ActiveRecord::Base belongs_to :field has_one :board, :through => :field has_one :content has_many :placed_avatars def move_to_trash self.trashcan = true end def recover_from_trash self.trashcan = false end def after_initialize if self.trashcan == nil self.trashcan = false end end def belongs_to_board board field.board.id == board.id end end
require 'minitest/autorun' require_relative '../lib/helpers.rb' class TestHelpers < Minitest::Test include Helpers def test_to_li assert_equal to_li("wag_bag"), "%li wag bag" end def test_underscores_to_whitespace assert_equal underscores_to_whitespace("wag_bag"), "wag bag" end def test_gen_dir_list assert_equal gen_dir_list(['.', '..', 'bag']), ['bag'] end def test_snake_to_title assert_equal snake_to_title('wag_a_bag'), 'Wag a bag' end end
class Account < ApplicationRecord include PenderData include CheckElasticSearch attr_accessor :source, :disable_es_callbacks, :disable_account_source_creation, :created_on_registration belongs_to :user, inverse_of: :accounts, optional: true belongs_to :team, optional: true has_many :medias has_many :account_sources, dependent: :destroy has_many :sources, through: :account_sources has_annotations before_validation :set_user, :set_team, on: :create validates_presence_of :url validate :validate_pender_result, on: :create, unless: :created_on_registration? validate :pender_result_is_a_profile, on: :create, unless: :created_on_registration? validates :url, uniqueness: true after_create :set_metadata_annotation, :create_source, :set_provider serialize :omniauth_info def user_id_callback(value, _mapping_ids = nil) user_callback(value) end def source_id_callback(value, _mapping_ids = nil) source = Source.where(name: value).last source.nil? ? nil : source.id end def data m = self.annotations('metadata').last&.load data = begin JSON.parse(m.get_field_value('metadata_value')) rescue {} end data || {} end def metadata self.data end def image self.metadata['picture'] || '' end def create_source source = self.source if source.nil? && Team.current.present? self.source = self.sources.where(team_id: Team.current.id).last return unless self.source.nil? end if source.nil? data = self.pender_data source = get_source_obj(data) source.update_from_pender_data(data) source.skip_check_ability = true source.save! end create_account_source(source) self.source = source end def get_source_obj(data) name = data['author_name'] unless data.nil? source = Source.create_source(name) unless name.blank? source = Source.new if source.nil? source end def refresh_account=(_refresh) self.pender_key = self.team.get_pender_key if self.team self.refresh_metadata self.sources.each do |s| s.updated_at = Time.now s.skip_check_ability = true s.save! end self.updated_at = Time.now end def self.create_for_source(url, source = nil, disable_account_source_creation = false, disable_es_callbacks = false, pender_key = nil) a = Account.where(url: url).last if a.nil? a = Account.new pender_key: pender_key a.disable_account_source_creation = disable_account_source_creation a.disable_es_callbacks = disable_es_callbacks a.source = source a.url = url if a.save return a else a2 = Account.where(url: a.url).last if a2.nil? a.save! return a end a = a2 end end unless a.nil? a.skip_check_ability = true a.pender_data = a.metadata a.source = source a.disable_account_source_creation = disable_account_source_creation a.disable_es_callbacks = disable_es_callbacks a.create_source end a end def created_on_registration? self.created_on_registration || (self.data && self.data['pender'] == false) end def set_omniauth_info_as_annotation m = self.annotations('metadata').last if m.nil? m = Embed.new m.annotation_type = 'metadata' m.annotated = self else m = m.load end m.metadata_for_registration_account(self.omniauth_info) end def refresh_metadata if self.created_on_registration? self.set_omniauth_info_as_annotation self.update_columns(url: self.data['url']) if self.data['url'] else self.refresh_pender_data end end def create_account_source(source) return if self.disable_account_source_creation self.sources << source self.skip_check_ability = true self.save! end private def set_user self.user = User.current unless User.current.nil? end def set_team self.team = Team.current unless Team.current.nil? end def pender_result_is_a_profile errors.add(:base, 'Sorry, this is not a profile') if !self.pender_data.nil? && self.pender_data['provider'] != 'page' && self.pender_data['type'] != 'profile' end def set_metadata_annotation self.created_on_registration ? set_omniauth_info_as_annotation : set_pender_result_as_annotation end def set_provider if self.provider.blank? data = self.data provider = data['provider'] unless self.data.nil? self.update_columns(provider: provider) unless provider.blank? end end end
class Portfolio < ApplicationRecord has_many :technologies accepts_nested_attributes_for :technologies, reject_if: :all_blank, allow_destroy: true include Placeholder validates_presence_of :title, :body, :main_image, :thumb_image scope :for_subtitile, -> (subtitle) { where('subtitle = ?', subtitle) } scope :by_position, -> { order('position ASC') } # scope :for_subtitile, -> (subtitle) { where(subtitle: subtitle) } # def self.react_on_rails # where(subtitle: "React On Rails") # end scope :for_ruby_on_rails, -> { where(subtitle: "Ruby On Rails") } after_initialize :set_defaults def set_defaults self.main_image ||= Placeholder.image_generator(600,400) self.thumb_image ||= Placeholder.image_generator(350,200) end end
class RecordsController < ApplicationController before_action :authenticate_user! def new @project = Project.find(params[:project_id]) @record = Record.new end def create @project = Project.find(params[:project_id]) @records = @project.records.create(record_params) redirect_to project_path(@project) end private def project_params params.require(:project).permit(:project_id, :name) end def record_params params.require(:record).permit(:duration_of_work, :record_date) end end
class Order < ApplicationRecord validates :order_date, presence: true has_many :purchases end
class DropLandsPlantsTable < ActiveRecord::Migration[5.1] def change drop_table :lands_plants end end
# # Cookbook Name:: basebox # Recipe:: default # # Copyright 2015, Etki # include_recipe 'locale' if node['basebox']['configure_locale'] if %w{ubuntu debian}.include? node['platform'] package 'iotop' end include_recipe 'git' if node['basebox']['install_git'] if node['basebox']['install_nginx'] include_recipe 'nginx' include_recipe 'nginx_conf' if node['basebox']['configure_nginx'] end include_recipe 'dnsmasq' if node['basebox']['install_dnsmasq'] if node['basebox']['install_mysql'] log 'Installing mysql' do level :info end mysql2_chef_gem 'default' do action :install end address = '0.0.0.0' if node['basebox']['expose_mysql'] else '127.0.0.1' mysql_service 'default' do bind_address node['basebox']['expose_mysql'] ? '0.0.0.0' : '127.0.0.1' initial_root_password node['basebox']['mysql_root_password'] charset 'utf8' action [:create, :start] end mysql_config 'default' do source 'mysite.cnf.erb' notifies :restart, 'mysql_service[default]' action :create end if not node['basebox']['mysql_users'].empty? or not node['basebox']['mysql_databases'].empty? mysql_connection_info = { :host => '127.0.0.1', :username => 'root', :password => node['basebox']['mysql_root_password'] } node['basebox']['mysql_databases'].keys.each do |name| mysql_database name do connection mysql_connection_info action :create end end node['basebox']['mysql_users'].each do |user, password| mysql_user user do connection mysql_connection_info password password action :create end node['basebox']['mysql_databases'].each do |name, details| if details['grants'].include? user mysql_user user do database_name name action :grant end end end end end end if node['basebox']['install_postgresql'] end include_recipe 'sqlite' if node['basebox']['install_sqlite'] if node['basebox']['install_redis'] include_recipe 'redis::install_from_package' end include_recipe 'memcached' if node['basebox']['install_memcached'] include_recipe 'gearman::server' if node['basebox']['install_gearman'] if node['basebox']['install_docker'] if node['kernel']['machine'] != 'x86_64' log "Docker may be installed only on `x64`-arch machine, while this one has ``#{node['kernel']['machine']}`` arch." do level :error end else include_recipe 'docker' if node['basebox']['install_docker'] end end include_recipe 'phantomjs' if node['basebox']['install_phantomjs'] include_recipe 'allure-cli' if node['basebox']['install_allure_cli']
require 'test_helper' class ScalesScalevaluesControllerTest < ActionController::TestCase setup do @scales_scalevalue = scales_scalevalues(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:scales_scalevalues) end test "should get new" do get :new assert_response :success end test "should create scales_scalevalue" do assert_difference('ScalesScalevalue.count') do post :create, scales_scalevalue: { id: @scales_scalevalue.id, scale_id: @scales_scalevalue.scale_id, scalevalues_id: @scales_scalevalue.scalevalues_id } end assert_redirected_to scales_scalevalue_path(assigns(:scales_scalevalue)) end test "should show scales_scalevalue" do get :show, id: @scales_scalevalue assert_response :success end test "should get edit" do get :edit, id: @scales_scalevalue assert_response :success end test "should update scales_scalevalue" do patch :update, id: @scales_scalevalue, scales_scalevalue: { id: @scales_scalevalue.id, scale_id: @scales_scalevalue.scale_id, scalevalues_id: @scales_scalevalue.scalevalues_id } assert_redirected_to scales_scalevalue_path(assigns(:scales_scalevalue)) end test "should destroy scales_scalevalue" do assert_difference('ScalesScalevalue.count', -1) do delete :destroy, id: @scales_scalevalue end assert_redirected_to scales_scalevalues_path end end
class ContestsController < ApplicationController def index @contests = Contest.all end def show @contest = Contest.find(params[:id]) end def new end def create @contest = Contest.new(contest_params) @contest.save redirect_to @contest end private def contest_params params.require(:contest).permit(:NameofContest, :ContestLevel, :ContestLocation, :NumberOfPlayers) end end
module Vertica module Messages class Query < FrontendMessage message_id ?Q def initialize(query_string) @query_string = query_string end def to_bytes message_string @query_string.to_cstring end end end end
class BookSuggestionSerializer < ActiveModel::Serializer attributes :id, :title, :author, :link, :user_id end
class JobsController < ApplicationController before_action :authenticate_user!, except: :show def show @job = Job.find(params[:id]) end def new @job = Job.new @companies = current_user.companies @categories = Category.all @contract_type = ContractType.all end def edit @job = Job.find(params[:id]) unless @job.company.user == current_user redirect_to root_path, alert: "User #{current_user.email} can't edit #{@job.company.name} jobs. This company belongs to another user." end unless @job.active? redirect_to @job end @companies = current_user.companies @categories = Category.all @contract_type = ContractType.all end def create @job = Job.new(job_params) if @job.save redirect_to @job else @categories = Category.all @companies = current_user.companies @contract_type = ContractType.all render new_job_path end end def update @job = Job.find(params[:id]) if @job.update(job_params) redirect_to @job else @categories = Category.all @companies = current_user.companies @contract_type = ContractType.all render edit_job_path end end private def job_params params.require(:job).permit(:title, :location, :company_id, :description, :category_id, :contract_type_id, :featured) end end
# desc "Explaining what the task does" # task :pyr_geo do # # Task goes here # end desc "Add geo location columns to a table" namespace :pyr_geo_engine do task :add_geo_cols, [:model_name] => :environment do |t, args| name = args[:model_name] system "rails g pyr:geo:add_to #{name}" end end desc "Load country information to the GeoName table from data files" namespace :pyr_geo_engine do task :load_country_info, [:country] => :environment do |t, args| name = args[:country] Pyr::Geo::Util::Loader::country(name) end end desc "Remove country information from the GeoName table" namespace :pyr_geo_engine do task :remove_country_info, [:country] => :environment do |t, args| name = args[:country] Pyr::Geo::Util::Loader::delete_country(name) end end desc "Load cities, lat,lng and population information to the GeoCity table from data files" namespace :pyr_geo_engine do task :load_cities, [:country] => :environment do |t, args| name = args[:country] Pyr::Geo::Util::Loader::cities(name) end end desc "Remove cities, lat,lng and population information from the GeoCity table" namespace :pyr_geo_engine do task :remove_cities, [:country] => :environment do |t, args| name = args[:country] Pyr::Geo::Util::Loader::delete_cities(name) end end
class HomeController < ApplicationController def index @tweets = Twitter.user_timeline count: 5 @events = CalendarEvent.order("date ASC").limit(3).where("date >= :start_date", {start_date: Date.today}) @about = Section.where("section_name='about'").first.section_content.split("\n").first end end
require 'rails_helper' RSpec.describe 'Sign in a User', type: :feature do scenario 'Signs in user' do visit new_user_registration_path fill_in 'Name', with: 'John' fill_in 'Email', with: 'John@example.com' fill_in 'Password', with: 'password' fill_in 'Password confirmation', with: 'password' click_on 'Sign up' click_on 'Sign Out' visit new_user_session_path fill_in 'Email', with: 'John@example.com' fill_in 'Password', with: 'password' click_on 'Log in' expect(page).to have_content('Success! Signed in successfully.') end scenario 'Invalid user inputs' do visit new_user_registration_path fill_in 'Name', with: 'John' fill_in 'Email', with: 'John@example.com' fill_in 'Password', with: 'password' fill_in 'Password confirmation', with: 'password' click_on 'Sign up' click_on 'Sign Out' visit new_user_session_path fill_in 'Email', with: 'John@example.com' fill_in 'Password', with: 'passwords' click_on 'Log in' expect(page).to have_content('Invalid Email or password.') end end
# validate new records against ISP Config DNS entries class DnsIspRecordValidator < ActiveModel::Validator # noinspection RubyResolve def validate(record) return if record.errors.count > 0 if record.new_record? || record.name_changed? || record.dns_zone_id_changed? record.errors[:dnszone] << 'Dnszone must selected' and return if record.dns_zone.nil? record.errors[:name] << 'No record name set' and return if record.name.blank? recs = record.dns_zone.isp_dnszone.find_record_by_name record.name if recs.length > 0 irecaid= record.dns_host_ip_a_record.isp_dns_a_record_id.to_s irecaaaaid = record.dns_host_ip_aaaa_record.isp_dns_aaaa_record_id.to_s aaaarecords = recs.find_all {|rec| rec.instance_of?(IspDnsAaaaRecord) && rec.id == irecaaaaid} arecords = recs.find_all {|rec| rec.instance_of?(IspDnsARecord) && rec.id == irecaid} if aaaarecords.length == 0 && arecords.length == 0 record.errors[:name] << 'This record name is in use' end end end end end
describe "Label View Test" do before(:all) do show_control :label_view @app = App.get_instance page = @app['labelViewsPage'] @label = page['basicLabel', LabelView] @foo_button = page['fooButton', ButtonView] @bar_button = page['barButton', ButtonView] @reset = page['resetButton', ButtonView] end before(:each) do @reset.click end it "will check a basic label's value" do @label.should have_value that_is_empty @foo_button.click @label.should have_value 'foo' @bar_button.click @label.should have_value /bar/i end end
require 'singleton' module Draftsman class Config include Singleton attr_accessor :serializer, :timestamp_field def initialize @timestamp_field = :created_at @mutex = Mutex.new @serializer = Draftsman::Serializers::Yaml end # Indicates whether Draftsman is on or off. Default: true. def enabled @mutex.synchronize { !!@enabled } end def enabled=(enable) @mutex.synchronize { @enabled = enable } end end end
spec = Gem::Specification.new do |s| s.name = 'dbconsole' s.version = '1.0.0' s.summary = "REPL for databases supported by ActiveRecord" s.description = %{REPL console for accessing and querying databases supported by ActiveRecord} s.files = Dir['lib/**/*.rb'] + Dir['test/**/*.rb'] s.require_path = 'lib' s.autorequire = 'dbconsole' s.has_rdoc = true s.extra_rdoc_files = Dir['[A-Z]*'] s.rdoc_options << '--title' << 'DB-Console -- A simple, powerful database console' s.author = "Jason Madigan" s.email = "jason@jasonmadigan.com" s.homepage = "http://jasonmadigan.com" end
$:.push File.expand_path("../lib", __FILE__) require "experiment/version" Gem::Specification.new do |s| s.name = 'experiment' s.version = Experiment::VERSION s.licenses = ['MIT'] s.summary = "A tool for running concurrent multi-configuration experiments" s.description = "A tool for running concurrent multi-configuration experiments. Quite often, we need to run different versions of an application to determine the effect of a change. Furthermore, to get statistically relevant results, we need to execute each experiment multiple times. For posteriority, we would also like to keep track of exactly how the application was run, how many times each version has been run, and what the exact changes were made to the application for each experiment.\nexperiment tries to solve this by integrating closely with version control systems, allowing developers to specify exactly which versions of the application to build, and what changes to apply (if any). It will execute each version multiple times, possibly concurrently, and report back when it finishes, leaving you to do other things than wait for one experiment to finish before starting the next." s.authors = ["Jon Gjengset"] s.email = 'jon@thesquareplanet.com' s.homepage = 'https://github.com/jonhoo/experiment' s.files = Dir.glob("{bin,lib}/**/*") + %w(LICENSE README.md) s.executables = ['experiment'] s.require_path = 'lib' s.add_runtime_dependency 'commander', '~> 4.2' s.add_runtime_dependency 'ruby-progressbar', '~> 1.5' s.add_runtime_dependency 'rugged', '~> 0.19' s.add_runtime_dependency 'colorize', '~> 0.7' end
require 'telegram/bot/rspec/integration/poller' RSpec.describe 'Integration spec helpers', telegram_bot: :poller do let(:bot) { Telegram::Bot::ClientStub.new('token') } let(:controller_class) do Class.new(Telegram::Bot::UpdatesController) do include Telegram::Bot::UpdatesController::CallbackQueryContext def callback_query(data = nil, *) answer_callback_query "data: #{data}" end def context_callback_query(data = nil, *) answer_callback_query "data: #{data}", extra: :param end def answer_and_edit_callback_query(data = nil, *) answer_callback_query "data: #{data}" edit_message :text, text: 'edited-text', extra: :param end end end describe '#callback_query', :callback_query do let(:data) { 'unknown:command' } it { should answer_callback_query("data: #{data}") } end describe '#context_callback_query', :callback_query do let(:data) { 'context:test:payload' } it { should answer_callback_query('data: test:payload', extra: :param) } it { should_not edit_current_message(:text) } end describe '#answer_and_edit_callback_query', :callback_query do let(:data) { 'answer_and_edit:test:payload' } it do should answer_callback_query(/test:payload/). and edit_current_message(:text, text: /edited/, extra: :param) end end end
# questo script mi permette di ottenere stringhe personalizzate per il sesso # del personaggio senza creare condizioni particolari e frasi multiple. # USO: Crea una stringa con una diversificazione di genere utilizzando gx # esempio: # %s è avvelenat\gx[o/a]! # applico string.gender(:male o :female) # Stamperà: # Francesco è avvelenato! -> se maschio # Monica è avvelenata! -> se femmina module GENREABLE_STRINGS GENDER_REGEX = /\\gx\[(.+\/.+)\]/i FEMALE_REGEX = /<female>/i FEMALE_ACTORS = [2,5,6,7,10,15,19] end class String # applica il genere ad una stringa preformattata # funziona solo su una singola parola per stringa. # @return [String] # @param [Symbol] gender_type def gender(gender_type = :male) if GENREABLE_STRINGS::GENDER_REGEX.match(self) apply_gender($1, gender_type) else self.clone end end # applica il genere ad una stringa preformattata # funziona solo su una singola parola per stringa. # metodo distruttivo. Modifica la stringa originale. # @return [String] # @param [Symbol] gender_type def gender!(gender_type = :male) if GENREABLE_STRINGS::GENDER_REGEX.match(self) self = apply_gender($1, gender_type) else self end end private # @param [String] substr def apply_gender(substr, gender_type) substr = substr.split('/') str = gender_type == :male ? substr.first : substr.last self.gsub(GENREABLE_STRINGS::GENDER_REGEX, str) end end class RPG::Enemy def gender @gender ||= init_gender end def init_gender GENREABLE_STRINGS::FEMALE_REGEX.match(self.note) ? :female : :male end end class Game_Battler # restituisce il sesso del personaggio # @return [Symbol] def gender :male end end class Game_Actor < Game_Battler # restituisce il sesso del personaggio # @return [Symbol] def gender GENREABLE_STRINGS::FEMALE_ACTORS.include?(@actor_id) ? :female : :male end end class Game_Enemy < Game_Battler # restituisce il sesso del personaggio # @return [Symbol] def gender enemy.gender end end
module Tokenizer class Lexer module TokenLexers def comp_2_conj?(chunk) chunk =~ /\Aで(あり)?\z/ end def tokenize_comp_2_conj(chunk, options = { reverse?: false }) comparison_tokens = comp_2_comparison_tokens raise Errors::UnexpectedInput, chunk if comparison_tokens.nil? if @context.last_token_type == Token::QUESTION if last_segment_from_stack.find { |t| t.type == Token::FUNCTION_CALL } @stack.pop # drop question else # truthy check comparison_tokens << Token.new(Token::RVALUE, ID_TRUE, sub_type: Token::VAL_TRUE) end end flip_comparison comparison_tokens if options[:reverse?] @stack.insert last_condition_index_from_stack, *comparison_tokens Token.new Token::COMP_2_CONJ # for flavour end end end end
require File.dirname(__FILE__) + '/../../test_helper' class Reputable::UserTest < ActiveSupport::TestCase context "when badging a Reputable::User through #badging_list" do before do @user = Factory :user @user.badgings.destroy_all Reputable::Badge::BADGES.each{|b| Reputable::Badge.find_or_create_by_name(b)} # ["Writer 5", "Writer 4", "Writer 3", "Writer 2", "Writer 1", "Top Reviewer"] end test 'should create all new badgings from a list when the user has no badgings' do assert_equal 0, @user.badgings.count @user.badging_list = { 0 => {:name => "Writer 1", :category_name=>"", :tier=>"4", :year=>"2010"}} @user.save @user.reload assert_equal 1, @user.badgings.count end test 'should create only the badgings the user does not have and leave an existing badge untouched' do badging = Factory :badging, :user => @user, :badge => Reputable::Badge.find_by_name('Writer 2') assert_equal 1, @user.badgings.count @user.badging_list = { 0 => {:name => "Writer 1", :category_name=>"", :tier=>"4", :year=>"2010"}, 1 => {:name => "Writer 3", :category_name=>"", :tier=>"3", :year=>"2010", :id => badging.id}} @user.save @user.reload badging.reload assert_equal 2, @user.badgings.count assert_equal ["Writer 1", "Writer 3"], @user.badges.map{|b| b.name}.sort #since writer 3 is existing one, the order mismatches and fails randomly assert_equal 'Writer 3', badging.badge.name end test 'should update the badgings when passed in ia badgings id' do badging = Factory :badging, :user => @user, :badge => Reputable::Badge.find_by_name('Writer 1') assert_equal 1, @user.badgings.count assert_equal false, @user.badges.map{|b| b.name}.include?('Writer 2') @user.badging_list = { 0 => {:name => "Writer 2", :category_name=>"", :tier=>"4", :year=>"2010", :id => badging.id }} @user.save @user.reload assert_equal 1, @user.badgings.count assert @user.badges.map{|b| b.name}.include?('Writer 2') assert_equal badging.id, @user.badgings.first.id end end end
# == Schema Information # # Table name: teams_employees # # id :integer not null, primary key # team_id :integer # employee_id :integer # created_at :datetime not null # updated_at :datetime not null # class TeamsEmployee < ActiveRecord::Base attr_accessible :employee_id, :team_id belongs_to :team belongs_to :employee end
module Cyclops class Window < FixedPanel attr_reader :overlay, :current_cursor # The main entry point. Creates an overlay to pack everything into. # Also creates a default mouse image unless another is specified. def initialize(*args) @@number_of_windows ||= 0 @overlay = Ogre::OverlayManager.instance.create("CyclopsEye#{@@number_of_windows+=1}") show args << nil # no parent. super(*args) if(@cursor.nil?) mouse do |cursor| cursor.image "default_cursor.png" end end @overlay.add_2d(@element) end # Set the mouse position to x,y. Range is 0-1 def mouse_position(x,y) if(@overlay.is_visible) @old_cursor = @current_cursor @current_cursor = cursor_at(x,y) child = visible_children(x,y).first if(@current_cursor) if(@old_cursor != @current_cursor) hide_cursor @current_cursor.show end @current_cursor.set_position(x, y) end # Used for mouse click events. @over_button = visible_children(x,y).find do |child| child.is_a?(Button) end end end # Press the mouse key, key def mouse_press(key) if(@overlay.is_visible) return unless @over_button @last_pressed = @over_button @over_button.press(key) end end # Release the mouse key, key def mouse_release(key) if @last_pressed && @over_button != @last_pressed @last_pressed.cancel @last_pressed = nil end if(@overlay.is_visible) return unless @over_button # release event @over_button.release(key) # click event @over_button.click(key) if @last_pressed == @over_button end end # Show all elements, including self def show @overlay.show end # Hide all elements, including self def hide @overlay.hide end end end
# With conditionals #class BeerSong # def verse(verse) # case verse # when 3..99 # "#{verse} bottles of beer on the wall, #{verse} bottles of beer.\n" \ # "Take one down and pass it around, #{verse - 1} bottles of beer on the wall.\n" # when 2 # "#{verse} bottles of beer on the wall, #{verse} bottles of beer.\n" \ # "Take one down and pass it around, #{verse - 1} bottle of beer on the wall.\n" # when 1 # "1 bottle of beer on the wall, 1 bottle of beer.\n" \ # "Take it down and pass it around, no more bottles of beer on the wall.\n" # when 0 # "No more bottles of beer on the wall, no more bottles of beer.\n" \ # "Go to the store and buy some more, 99 bottles of beer on the wall.\n" # end # end # # def verses(starting_verse, stopping_verse) # starting_verse.downto(stopping_verse).map { |current| verse(current) }.join("\n") # end # # def lyrics # verses(99, 0) # end #end # Replacing conditionals with polymorphism class BeerSong class ZeroVerses def verse(_count) "No more bottles of beer on the wall, no more bottles of beer.\n" \ "Go to the store and buy some more, 99 bottles of beer on the wall.\n" end end class OneVerse def verse(_count) "1 bottle of beer on the wall, 1 bottle of beer.\n" \ "Take it down and pass it around, no more bottles of beer on the wall.\n" end end class TwoVerses def verse(_count) "2 bottles of beer on the wall, 2 bottles of beer.\n" \ "Take one down and pass it around, 1 bottle of beer on the wall.\n" end end class RegularVerses def verse(count) "#{count} bottles of beer on the wall, #{count} bottles of beer.\n" \ "Take one down and pass it around, #{count - 1} bottles of beer on the wall.\n" end end VERSE_CLASSES = Hash.new(RegularVerses).merge({ 0 => ZeroVerses, 1 => OneVerse, 2 => TwoVerses }) def verse(count) VERSE_CLASSES[count].new.verse(count) end def verses(starting_verse, stopping_verse) starting_verse.downto(stopping_verse).map { |current| verse(current) }.join("\n") end def lyrics verses(99, 0) end end
class Song attr_accessor :artist, :name def initialize(name) @name = name end def artist_name=(name) self.artist = Artist.new(name) end def self.new_by_filename(file_name) split = file_name.split(" - ") artist = split[0] song = split[1] new_song = self.new(song) new_song.artist = Artist.find_or_create_by_name(artist) new_song end end
class SysModuleMapping < ActiveRecord::Base belongs_to :sys_user_group belongs_to :sys_module attr_accessible :sys_module_id, :sys_user_group_id, :as => :role_new validates_presence_of :sys_module_id validates_presence_of :sys_user_group_id end
require 'digest/md5' require 'cgi' module ActiveMerchant #:nodoc: module Billing #:nodoc: module Integrations #:nodoc: module Alipay module Sign def verify_sign? clone = @params.clone sign_type = clone.delete("sign_type") sign = clone.delete("sign") md5_string = clone.sort.collect do |s| s[0]+"="+CGI.unescape(s[1]) end Digest::MD5.hexdigest(md5_string.join("&") + Alipay.key) == sign.downcase end end end end end end
class User < ApplicationRecord has_secure_password VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i validates :name, :email, presence: true validates :email, format: { with: VALID_EMAIL_REGEX } end
Given(/^I login with single account and select specified transaction based on "([^"]*)", "([^"]*)", "([^"]*)" and "([^"]*)"$/) do |postdate, merchant, category, amount| visit(LoginPage) on(LoginPage) do |page| login_data = page.data_for(:dispute_single_disputable_ods) username = login_data['username'] password = login_data['password'] ssoid = login_data['ssoid'] page.login(username, password, ssoid) end @authenticated = on(DisputesPage).is_summary_shown? if @authenticated[0] == false fail("#{@authenticated[1]}" "--" "#{@authenticated[2]}") end visit(TransactionsDetailsPage) on(DisputesPage) do |page| txn_range = ['Date_Range',postdate, postdate] sort_by = ['Categories',category] page.file_a_dispute_based_on_txn_matching_date_range_and_sort_option(postdate, merchant, category, amount,nil,sort_by) end end Then(/^the page will display either the fraud Call Us dialog box or the 'Do you have more than one transaction you do not recognize\?' radio button$/) do puts on(DisputesPage).call_us_text.exist? puts on(DisputesPage).do_you_have_more_than_one_transaction_you_do_not_recognize_question_element.exist? if on(DisputesPage).on(DisputesPage).call_us_text_DNR.exists? equal? true puts "call us text displayed" elsif on(DisputesPage).do_you_have_more_than_one_transaction_you_do_not_recognize_question_element.exists? equal? true puts "do you have question" end end Then(/^the page will display the following message at the top of the page in red font 'Our dispute entry system is experiencing technical difficulties\. Unfortunately, we did not receive your dispute details\. If you'd like to submit your dispute online again later, please do\. Or if it is more convenient, you may call our Capital One Fraud Solutions Department at 1\-800\-887\-8643\. We're available seven days a week from (\d+) a\.m\. to (\d+) p\.m\. EST \(Ref No\. (\d+)\.(\d+)\)'$/) do |arg1, arg2, arg3, arg4| puts on(DisputesPage).rtm_errors on(DisputesPage).rtm_errors.should == "Our dispute entry system is experiencing technical difficulties. Unfortunately, we did not receive your dispute details. If you'd like to submit your dispute online again later, please do. Or if it is more convenient, you may call our Capital One Fraud Solutions Department at 1-800-887-8643. We're available seven days a week from #{arg1} a.m. to #{arg2} p.m. EST. (Ref No. #{arg3}.#{arg4})" end
require File.dirname(__FILE__) + '/../test_helper' require 'users_controller' # Re-raise errors caught by the controller. class UsersController; def rescue_action(e) raise e end; end class UsersControllerTest < Test::Unit::TestCase fixtures :users, :account_types def setup @controller = UsersController.new @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new @account_type = account_types(:free) @payment_types = PaymentType.find(:all, :order => "name" ).map {|p| [p.name, p.id] } end def test_should_get_index get :index assert_response :success assert assigns(:users) end def test_should_get_new get :new, {:account_type_id => @account_type} assert_response :success end def test_should_create_user old_count = User.count post :create, :user => {:login => 'quire', :email => 'quire@example.com', :password => 'quire', :password_confirmation => 'quire' }, :account_type => {:id => @account_type} assert_equal old_count+1, User.count assert_redirected_to :controller => "site", :action => :index end def test_should_show_user get :show, :id => 1 assert_response :success end def test_should_get_edit get :edit, :id => 1 assert_response :success end def test_should_update_user put :update, :id => 1, :user => { } assert_redirected_to user_path(assigns(:user)) end def test_should_destroy_user old_count = User.count delete :destroy, :id => 1 assert_equal old_count-1, User.count #assert_redirected_to users_path end protected def create_user(options = {}) User.create({ :login => 'quire', :email => 'quire@example.com', :password => 'quire', :password_confirmation => 'quire' }.merge(options)) end end
class TranslationOption attr_accessor :code, :description cattr_accessor :translated, :untranslated, :unsourced def initialize(code, description) @code, @description = code, description end def self.all [untranslated, translated, unsourced] end def self.translated @@translated ||= TranslationOption.new('translated', 'Translated') end def self.untranslated @@untranslated ||= TranslationOption.new('untranslated', 'Untranslated') end def self.unsourced @@unsourced ||= TranslationOption.new('unsourced', 'Unsourced') end def self.find(code) all.detect{|option| option.code == code} || untranslated end end
class CreateInterventions < ActiveRecord::Migration def change create_table :interventions do |t| t.references :collective, index: true, foreign_key: true t.string :name, null: false, default: '' t.text :description t.string :place t.datetime :schedule t.string :event_link t.timestamps null: false end end end
class CreateUsers < ActiveRecord::Migration[5.2] def change create_table :users do |t| t.string :username #it must be named like this in order to user bcrypt t.string :password_digest t.timestamps end end end
module Tarot module Entities class Correspondence < Entity attr_reader :golden_dawn def initialize(options) @golden_dawn = set_attribute options, :golden_dawn end private def set_attribute(options, name) options.fetch(name) do msg = "Missing required correspondence: #{name}" raise ArgumentError, msg end end end end end
require 'rails_helper' RSpec.describe BuyShipping, type: :model do describe '商品購入' do before do user = FactoryBot.create(:user) product = FactoryBot.create(:product) @buy_shipping = FactoryBot.build(:buy_shipping, user_id: user.id, product_id: product.id) sleep(1) end context '商品が購入出来る場合' do it '全て正しく入力されていれば保存出来ること' do expect(@buy_shipping).to be_valid end it 'buildingは空でも保存出来ること' do @buy_shipping.building = '' expect(@buy_shipping).to be_valid end end context '商品が購入出来ない場合' do it 'postal_codeが空だと保存できないこと' do @buy_shipping.postal_code = '' @buy_shipping.valid? expect(@buy_shipping.errors.full_messages).to include("Postal code can't be blank") end it 'postal_codeが半角のハイフンを含んだ正しい形式でないと保存できないこと' do @buy_shipping.postal_code = '1234567' @buy_shipping.valid? expect(@buy_shipping.errors.full_messages).to include('Postal code is invalid. Include hyphen(-)') end it 'area_idが空では保存できないこと' do @buy_shipping.area_id = '' @buy_shipping.valid? expect(@buy_shipping.errors.full_messages).to include("Area can't be blank") end it 'area_idが1では登録できない' do @buy_shipping.area_id = 1 @buy_shipping.valid? expect(@buy_shipping.errors.full_messages).to include("Area must be other than 1") end it 'cityが空では保存できないこと' do @buy_shipping.city = '' @buy_shipping.valid? expect(@buy_shipping.errors.full_messages).to include("City can't be blank") end it 'streetが空では保存できないこと' do @buy_shipping.street = '' @buy_shipping.valid? expect(@buy_shipping.errors.full_messages).to include("Street can't be blank") end it 'phone_numberが空では保存できないこと' do @buy_shipping.phone_number = '' @buy_shipping.valid? expect(@buy_shipping.errors.full_messages).to include("Phone number can't be blank") end it 'phone_numberは11桁以内出ないと保存できないこと' do @buy_shipping.phone_number = '090123456789' @buy_shipping.valid? expect(@buy_shipping.errors.full_messages).to include("Phone number is invalid") end it 'phone_numberは数値のみでないと保存できないこと' do @buy_shipping.phone_number = '090-1234-5678' @buy_shipping.valid? expect(@buy_shipping.errors.full_messages).to include("Phone number is invalid") end it 'phone_numberは数値のみでないと保存できないこと(英数字混合)' do @buy_shipping.phone_number = '0901234567a' @buy_shipping.valid? expect(@buy_shipping.errors.full_messages).to include("Phone number is invalid") end it 'phone_numberは全角数字では保存できないこと' do @buy_shipping.phone_number = '09012345678' @buy_shipping.valid? expect(@buy_shipping.errors.full_messages).to include("Phone number is invalid") end it 'userが紐付いていないと保存できないこと' do @buy_shipping.user_id = nil @buy_shipping.valid? expect(@buy_shipping.errors.full_messages).to include("User can't be blank") end it 'productが紐付いていないと保存できないこと' do @buy_shipping.product_id = nil @buy_shipping.valid? expect(@buy_shipping.errors.full_messages).to include("Product can't be blank") end it 'tokenが空では保存できないこと' do @buy_shipping.token = nil @buy_shipping.valid? expect(@buy_shipping.errors.full_messages).to include("Token can't be blank") end end end end
module ChainReactor require 'reaction' # Contains the map of reactions and allowed client addresses. # # This is used to determine which clients are allowed to connect, and to # dispatch reactions. class Reactor # Pass a logger object and define an empty address map. def initialize(logger) @address_map = {} @log = logger end # Add a react_to block from the chain file. # # Creates a Reaction object and calls add_address(). def add(addresses,options,block) reaction = Reaction.new(options,block,@log) addresses.each { |addr| add_address(addr,reaction) } end # Add an address with a reaction. def add_address(address,reaction) @log.debug { "Linking reaction to address #{address}" } if @address_map.has_key? address @address_map[address] << reaction else @address_map[address] = [reaction] end end # React to a client by running the associated reactions. # # Raises an error if the address is not allowed - use # address_allowed? first. def react(address,data_string) address_allowed?(address) or raise 'Address is not allowed' @address_map[address].each do |reaction| @log.info { "Executing reaction for address #{address}" } begin reaction.execute(data_string) rescue Parsers::ParseError => e @log.error { "Parser error: #{e.message}" } rescue Parsers::RequiredKeyError => e @log.error { "Client data invalid: #{e.message}" } rescue ReactionError => e @log.error { 'Exception raised in reaction: '+e.message } end end end # Get an array of reactions for a given address def reactions_for(address) @address_map[address] if address_allowed?(address) end # Check whether the IP address is allowed. # # An IP address is allowed if the chain file specifies a "react_to" block # with that address. def address_allowed?(address) @address_map.has_key? address end end end
class UsersController < ApplicationController before_filter :authenticate_user! def show @user = current_user @person = @user.person end end
class Api::V1::SessionsController < ApiController skip_before_action :check_token def create email = params[:email] password = params[:password] @user = User.where(email: email).first if @user && @user.authenticate(password) render json: { token: @user.token } else render json: { error: 'Username or password is incorrect' }, status: 401 end end end
# Static pages. class HomeController < ApplicationController respond_to :html, :xml def index @current = Location.current @post = Post.published.first end def map # Nothin' to do! Hooray! end def about @states = State.where(done: true) @finished = Experience.done end def colophon @users = User.order('created_at DESC').registered end def sitemap fetch_latest_objects @pages = [home_xml, map_xml(@experience), blog_xml(@post), about_xml(@post)] @pages += posts_xml + experiences_xml + users_xml respond_to { |format| format.xml } end private def fetch_latest_objects @post = Post.published.first @experience = Experience.order('created_at DESC').first end def home_xml { url: '/', updated_at: xml_date(Location.current.updated_at), changefreq: 'daily', priority: '1.0' } end def map_xml(exp) { url: map_path, updated_at: xml_date(exp.created_at), changefreq: 'daily', priority: '1.0' } end def blog_xml(post) { url: posts_path, updated_at: xml_date(post.published_at), changefreq: 'daily', priority: '1.0' } end def about_xml(post) { url: about_path, updated_at: xml_date(post.published_at), changefreq: 'weekly', priority: '1.0' } end def posts_xml Post.published.all.map do |p| { url: post_path(p), updated_at: xml_date(p.published_at), changefreq: 'daily', priority: '0.7' } end end def experiences_xml Experience.popular.map do |e| { url: experience_path(e), updated_at: xml_date(e.created_at), changefreq: 'daily', priority: '0.6' } end end def users_xml User.all.map do |u| { url: "/map/ambassadors/#{u.uuid}", updated_at: xml_date(u.created_at), changefreq: 'daily', priority: '0.5' } end end def xml_date(time) time.strftime('%Y-%m-%dT%H:%M:%S+00:00') end end
require 'test_helper' class Manage::AdminsControllerTest < ActionDispatch::IntegrationTest setup do @manage_admin = manage_admins(:one) end test "should get index" do get manage_admins_url assert_response :success end test "should get new" do get new_manage_admin_url assert_response :success end test "should create manage_admin" do assert_difference('Manage::Admin.count') do post manage_admins_url, params: { manage_admin: { name: @manage_admin.name, number: @manage_admin.number, password_digest: @manage_admin.password_digest, role: @manage_admin.role } } end assert_redirected_to manage_admin_url(Manage::Admin.last) end test "should show manage_admin" do get manage_admin_url(@manage_admin) assert_response :success end test "should get edit" do get edit_manage_admin_url(@manage_admin) assert_response :success end test "should update manage_admin" do patch manage_admin_url(@manage_admin), params: { manage_admin: { name: @manage_admin.name, number: @manage_admin.number, password_digest: @manage_admin.password_digest, role: @manage_admin.role } } assert_redirected_to manage_admin_url(@manage_admin) end test "should destroy manage_admin" do assert_difference('Manage::Admin.count', -1) do delete manage_admin_url(@manage_admin) end assert_redirected_to manage_admins_url end end
class AddAttachmentCitypicToCities < ActiveRecord::Migration def self.up change_table :cities do |t| t.attachment :citypic end end def self.down remove_attachment :cities, :citypic end end
class Admin::CategoriesController < AdminController def new @category = Category.new end def create @category = Category.new(category_params) @category.save redirect_to admin_items_path end def category_params params.require(:category).permit(:name) end end
class CreatePublicFolderConnections < ActiveRecord::Migration def change create_table :public_folder_connections do |t| t.references :folder t.references :site_setting t.integer :order t.timestamps end add_index :public_folder_connections, :folder_id end end
require 'pry' def dictionary(word = "For") words = { "hello" => "hi", "to" => "2", "two" => "2", "too" => "2", "for" => "4", "four" => "4", "be" => "b", "you" => "u", "at" => "@", "and" => "&" } return words.key?(word.downcase) ? words[word.downcase] : word # if words.key?(word) # return words[word] # else # return word # end end def word_substituter(tweet) new_array = [] tweet_array = tweet.split tweet_array.each_with_index do |word, index| new_array << dictionary(word) end new_array.join (" ") end def bulk_tweet_shortener(tweet_array) tweet_array.each do |string| puts word_substituter(string) end end def selective_tweet_shortener(tweet_string) return tweet_string.length > 140 ? word_substituter(tweet_string) : tweet_string # if tweet_string.length > 140 # return word_substituter(tweet_string) # else # return tweet_string # end end def shortened_tweet_truncator(tweet_string) if tweet_string.length > 140 shortened_tweet = word_substituter(tweet_string) if shortened_tweet.length > 140 return shortened_tweet[0..136].concat("...") else return shortened_tweet end else return tweet_string end end
class Comment < ApplicationRecord validates :body, presence: true, length: {minimum: 5} validates :product_id, presence: true belongs_to :product end
module Ricer::Net class Message include Ricer::Base::Base SCOPES_CHANNEL ||= [:bot, :server, :channel, :user] SCOPES_PRIVATE ||= [:bot, :server, :user] attr_reader :raw, :time attr_reader :pipeplugs, :pipelines attr_accessor :prefix, :server attr_accessor :sender, :receiver, :command, :args attr_accessor :reply_to, :reply_prefix, :reply_data # These are set when there is a reply for this msg generated, else all are nil attr_accessor :plugin, :commandline, :errorneous def processed?; @processed; end def unprocessed?; !@processed; end def processed=(bool) @processed = bool ? true : false; end def reply_encoding_iso reply_to.nil? ? (server.encoding || bot.encoding).to_label : (reply_to.encoding || server.encoding || bot.encoding).to_label end def self.fake_message(server, text=nil, reply_to=nil) #bot.log_debug("Net/Message::fake_message(#{server.displayname})") # Create a message, but don´t remember in thread old_message = Thread.current[:ricer_message] # old remembered message = new(nil) # the new fake Thread.current[:ricer_message] = old_message if old_message # restore message.server = server message.sender = bot message.receiver = bot message.reply_to = reply_to||server message.reply_text(text||'Somethings wrong!') end def initialize(rawmessage=nil) #bot.log_debug("Net/Message#new(#{rawmessage}) NEW!") Thread.current[:ricer_message] = self @time = Time.new @raw = rawmessage end def to_s if incoming? super + ":O <= " + @raw else super + ":] => " + @reply_data end end def incoming?; @reply_data.nil? end def outgoing?; !incoming?; end def self.outgoing(to, command, argline) message = new() message.server = to.server message.command = command message.sender = bot message.receiver = to message.commandline = argline end def hostmask #bot.log_debug("Message#hostmask returns #{prefix.rsubstr_from('@')}") prefix.rsubstr_from('@') end def is_ricer? is_user? && sender.is_ricer? end def is_user? sender && (sender.is_a?(Ricer::Irc::User)) end def is_server? receiver && (receiver.is_a?(Ricer::Irc::Server)) end def is_channel? receiver && (receiver.is_a?(Ricer::Irc::Channel)) end def is_query? receiver.nil? || (receiver.is_a?(Ricer::Irc::User)) end def channel current_message.is_channel? ? receiver : nil end def channel_id current_message.is_channel? ? receiver.id : nil end def scope is_channel? ? Ricer::Irc::Scope::CHANNEL : Ricer::Irc::Scope::USER end def scopes is_channel? ? SCOPES_CHANNEL : SCOPES_PRIVATE end def is_triggered? return false if privmsg_line == "" return true if is_query? # return false unless is_channel? return (receiver.triggers||server.triggers).include?(privmsg_line[0]) end def is_trigger_char? trigger_chars.include?(privmsg_line[0]) end def trigger_chars is_query? ? server.triggers : receiver.triggers||server.triggers end def trigger_char trigger_chars[0] rescue '' end def reply_text(text) (self.reply_data, @time = text, Time.now) and return self end def reply_message(text) self.clone.reply_text(text) end def reply_clone #self.clone.setup_reply self.setup_reply end def setup_reply self.reply_prefix = reply_prefix_text self.setup_target(reply_target) end def setup_target(target) self.reply_to = target self end def target self.reply_to end def reply_target is_query? ? sender : receiver end def reply_prefix_text is_channel? ? "#{sender.name}: ": '' end def privmsg_line args[1] end ############# ### Pipes ### ############# def forked! @forked ||= 0 @forked += 1 @forked end def forked? @forked ||= 0 @forked > 0 end def joined! @forked ||= 0 @forked -= 1 @forked end def clone_chain next_message = self.clone next_message.args = self.args.clone next_message.clean_chain end def clean_chain @pipeout = '' @pipeplugs, @pipelines, @chainplugs = [], [], [] self end def add_chainline(message) #bot.log_debug("Message#add_chainline(#{message.args[1]})") @chainplugs ||= [] @chainplugs.push(message) self end def add_pipeline(plugin, line) @pipeout ||= '' @pipeplugs ||= []; @pipelines ||= [] @pipeplugs.push(plugin); @pipelines.push(line) #bot.log_debug("Message#add_pipeline(#{line}) to #{self.args[1]}. Chains: #{@chainplugs.length rescue 0}. Pipes: #{@pipeplugs.length}") self end def chain_message return nil if (@errorneous) || (@chainplugs.nil?) || (@chainplugs.length == 0) #bot.log_debug("Polling next chained command: #{@chainplugs[0].args[1]}") @chainplugs.shift end def chained? (!@errorneous) && (@chainplugs) && (@chainplugs.length > 0) end def chain! next_message = chain_message # Copy data self.args[1] = next_message.args[1] self.plugin = next_message.plugin @pipeout = '' @pipelines = next_message.pipelines @pipeplugs = next_message.pipeplugs #bot.log_debug("Next chained command: #{self.args[1]}. Pipes: #{@pipeplugs.length rescue 0}") self.plugin.exec_plugin return true end def pipe?(text=nil) return false if @errorneous || @pipelines.nil? || (@pipelines.length == 0) @pipeout += text + "\n" if text return true end def pipe! plugin = @pipeplugs.shift line = @pipelines.shift + ' ' + @pipeout self.args[1] = line.rtrim("\n") @pipeout = '' #bot.log_debug("Next piped command: #{self.args[1]}. Pipes left: #{@pipeplugs.length}") plugin.exec_plugin return true end end end
class AssetDeal < ApplicationRecord belongs_to :country, optional: true belongs_to :offshore_field, optional: true belongs_to :buyer, class_name: Company.name, optional: true belongs_to :seller, class_name: Company.name, optional: true end
module Mondavi class IsComponentLocal include Operation def initialize(target_concept:) @target_concept = target_concept end def call() # TODO: May need to make this more robust impl = @target_concept.to_s.gsub("Api", "ApiImpl") Object.const_get(impl).present? rescue NameError => e false end private attr_accessor :target_concept end end
class Video < ApplicationRecord has_many :messages, primary_key: :chat_id, foreign_key: :chat_id, class_name: :Message def self.set(response) video = find_or_create_by(video_id: response['id']) video.title = response['snippet']['title'] video.concurrent_viewers = response['liveStreamingDetails']['concurrentViewers'] video.chat_id = response['liveStreamingDetails']['activeLiveChatId'] video.save! video end end
# frozen_string_literal: true require 'rails_helper' RSpec.describe TokenController, type: :controller do before do @user = FactoryBot.create(:user, admin: true) session[:user_id] = @user.id end describe 'GET #index' do it 'returns http success' do get :index, params: { user_id: @user.id } expect(response).to have_http_status(:success) end end describe 'POST #update' do it 'returns http redirect' do post :update, params: { user_id: @user.id } expect(response).to have_http_status(302) end end end
class Rating G = :G PG = :PG PG13 = :PG13 R = :R NC17 = :NC17 def self.minimum_age_for(rating) age_mapping = {:G => 0, :PG => 0, :PG13 => 13, :R => 17, :NC17 => 18} age_mapping[rating] end end
class V1::ApplicationController < ActionController::Base respond_to :json # before_filter :default_json def sanitized_params resource = self.class.name.demodulize.gsub("Controller", "").downcase.singularize.to_sym @sanitized_params ||= (params[resource] ? params.require(resource) : params).permit(*permitted_params) end def after_sign_in_path_for(resource_or_scope) dashboard_url end def current_account current_user.account end helper_method :current_account protected def default_json request.format = :json if params[:format].nil? end def auth! unless params[:auth_token] && user_signed_in? render json: {}, status: 401 end end end
class Course < ActiveRecord::Base validates :number, :title, presence: true validates :enrollment_capacity, numericality: {greater_than_or_equal_to: 1}, presence: true has_many :enrollments has_many :students, through: :enrollments def enrollment_count(course_term) enrollments.find_all { |enrollment| enrollment.course_term == course_term }.count end def enrollable?(course_term) enrollment_count(course_term) < enrollment_capacity end def to_s "#{number}: #{title}" end end
require "sinatra" require "sinatra/reloader" if development? require "sinatra/content_for" require "tilt/erubis" require "pry" configure do enable :sessions set :session_secret, 'secret' set :erb, :escape_html => true end helpers do def count_completed_todos(todos) todos.select do |todo| todo[:completed] end.count end def count_remaining_todos(todos) todos.size - count_completed_todos(todos) end def all_todos_complete?(todos) if !todos.empty? return count_completed_todos(todos) == todos.size end false end def list_class(list) "complete" if all_todos_complete?(list) end # def add_orig_index(list) # orig_index_addon = {} # orig_idx = 0 # list.each do |key, _| # orig_index_addon[key] = orig_idx # orig_idx += 1 # end # orig_index_addon # end def sort_lists(lists) # add_orig_index(lists).sort_by do |arr_item| # item = arr_item.first # all_todos_complete?(item[:todos]) ? 1 : 0 # end lists.sort_by do |item| all_todos_complete?(item[:todos]) ? 1 : 0 end end def sort_todos(todos) # add_orig_index(todos).sort_by do |arr_item| # item = arr_item.first # item[:completed] ? 1 : 0 # end todos.sort_by do |item| item[:completed] ? 1 : 0 end end end before do session[:lists] ||= [] end # Return error msg if name invalid. Return nil if name valid. def error_for_list_name(name) if !(1..100).cover?(name.size) "List name must be between 1 and 100 characters" elsif session[:lists].any? { |list| list[:name] == name } "List name must be unique" end end # Return error msg if name invalid. Return nil if name valid def error_for_todo(name) if !(1..100).cover?(name.size) "Todo must be between 1 and 100 characters" end end def validate_list(list_id) if session[:lists].select{|list| list[:id] == list_id}.first return session[:lists].select{|list| list[:id] == list_id}.first else session[:error] = "The specified list was not found." redirect "/lists" end end def next_todo_id(todos) max = todos.map {|todo| todo[:id] }.max || 0 max + 1 end def next_list_id(lists) max = lists.map {|list| list[:id] }.max || 0 max + 1 end get "/" do redirect "/lists" end # View list of lists get "/lists" do @lists = session[:lists] erb :lists, layout: :layout end # Render the new list form get "/lists/new" do erb :new_list, layout: :layout end # Create a new list post "/lists" do list_name = params[:list_name].strip lists = session[:lists] error = error_for_list_name(list_name) if error session[:error] = error erb :new_list, layout: :layout else list_id = next_list_id(lists) lists << { id: list_id, name: list_name, todos: [] } session[:success] = "The list has been created." redirect "/lists" end end # Show single list and its todos get "/lists/:id" do @list_id = params[:id].to_i @list = validate_list(@list_id) erb :list, layout: :layout end # Render the edit list form get "/lists/:id/edit" do list_id = params[:id].to_i @list = validate_list(list_id) erb :edit_list, layout: :layout end # Update/edit list information post "/lists/:id" do @list_id = params[:id].to_i @list = validate_list(@list_id) list_name = params[:list_name].strip error = error_for_list_name(list_name) if error session[:error] = error erb :edit_list, layout: :layout else @list[:name] = list_name session[:success] = "The list has been updated." redirect "/lists/#{@list_id}" end end # Delete a list post "/lists/:id/delete" do @list_id = params[:id].to_i lists = session[:lists] lists.delete_if{|list| list[:id] == @list_id} if env["HTTP_X_REQUESTED_WITH"] == "XMLHttpRequest" # ajax "/lists" else session[:success] = "The list has been deleted." redirect "/lists" end end # Add new todo to list post "/lists/:list_id/todos" do @list_id = params[:list_id].to_i @list = validate_list(@list_id) todo_name = params[:todo].strip error = error_for_todo(todo_name) if error session[:error] = error erb :list, layout: :layout else todo_id = next_todo_id(@list[:todos]) @list[:todos] << { id: todo_id, name: todo_name, completed: false } session[:success] = "The todo has been added." redirect "/lists/#{@list_id}" end end # Delete a todo from list post "/lists/:list_id/todos/:todo_id/delete" do @list_id = params[:list_id].to_i todo_id = params[:todo_id].to_i @list = validate_list(@list_id) @list[:todos].delete_if{|todo| todo[:id] == todo_id} if env["HTTP_X_REQUESTED_WITH"] == "XMLHttpRequest" # ajax status 204 else session[:success] = "The todo has been deleted." redirect "/lists/#{@list_id}" end end # Update completion status of todo post "/lists/:list_id/todos/:todo_id/check" do @list_id = params[:list_id].to_i todo_id = params[:todo_id].to_i @list = validate_list(@list_id) is_completed = params[:completed] == "true" selected_todo = @list[:todos].select{|todo| todo[:id] == todo_id}.first selected_todo[:completed] = is_completed redirect "/lists/#{@list_id}" end # Update all todos as complete post "/lists/:list_id/todos/complete_all" do @list_id = params[:list_id].to_i @list = validate_list(@list_id) @list[:todos].each do |todo| todo[:completed] = true end session[:success] = "All the todos have been completed." redirect "/lists/#{@list_id}" end
class RMQ # I'm purposly not including Enumerable, # please use to_a if you want one # @return [RMQ] def <<(value) selected << value if value.is_a?(UIView) self end def empty? selected.length == 0 end alias :is_blank? :empty? # @return [RMQ] # # @example # rmq(UILabel)[3] # or # rmq(UILabel)[1..5] # or # rmq(UILabel)[2,3] def [](*args) RMQ.create_with_array_and_selectors(Array(selected[*args]), @selectors, @originated_from) end alias :eq :[] # @return [RMQ] def each(&block) return self unless block RMQ.create_with_array_and_selectors(selected.each(&block), @selectors, @originated_from) end # @return [RMQ] def map(&block) return self unless block RMQ.create_with_array_and_selectors(selected.map(&block), @selectors, @originated_from) end alias :collect :map # @return [RMQ] def select(&block) return self unless block RMQ.create_with_array_and_selectors(selected.select(&block), @selectors, @originated_from) end # @return [RMQ] def detect(&block) # Unlike enumerable, detect and find are not the same. See find in transverse return self unless block RMQ.create_with_array_and_selectors(selected.select(&block), @selectors, @originated_from) end # @return [RMQ] def grep(&block) return self unless block RMQ.create_with_array_and_selectors(selected.grep(&block), @selectors, @originated_from) end # @return [RMQ] def reject(&block) return self unless block RMQ.create_with_array_and_selectors(selected.reject(&block), @selectors, @originated_from) end # @return [RMQ] def inject(o, &block) return self unless block RMQ.create_with_array_and_selectors(selected.inject(o, &block), @selectors, @originated_from) end alias :reduce :inject # @return [RMQ] def first # TODO, check if it fails with nil RMQ.create_with_array_and_selectors([selected.first], @selectors, @originated_from) end # @return [RMQ] def last # TODO, check if it fails with nil RMQ.create_with_array_and_selectors([selected.last], @selectors, @originated_from) end # @return [Array] def to_a selected end # @return [Integer] number of views selected def length selected.length end def size length end def count length end #alias :size :length #alias :count :length end
require_relative 'expr' require_relative 'token' class AstPrinter def print(expr) return expr.accept(self) end def visit_binary_expr(expr) return parenthesize(expr.operator.lexeme, expr.left, expr.right) end def visit_grouping_expr(expr) return parenthesize('group', expr.expression) end def visit_literal_expr(expr) return "nil" if expr.value == nil return expr.value.to_s end def visit_unary_expr(expr) return parenthesize(expr.operator.lexeme, expr.right) end def parenthesize(name, *exprs) expression = '(' + name exprs.each do |expr| expression.concat(' ') expression.concat(expr.accept(self)) end expression.concat(')') return expression end end # expression = Expr::Binary.new( # Expr::Unary.new( # Token.new(:minus, '-', nil, 1), # Expr::Literal.new(123)), # Token.new(:star, '*', nil, 1), # Expr::Grouping.new(Expr::Literal.new(45.67)) # ) # printer = AstPrinter.new # puts printer.print(expression)
require "uri" require "net/http" require "json" # To send get or post request with custom payload. # # Usage: # => hello = XmlRequest.new( uri ) # => hello.get({service: "SOS", request: "GetCapabilities"}) # class XmlRequest attr_accessor :uri, :packet, :post def initialize(url) @uri = url @packet = Net::HTTP.new(uri.host, uri.port) @query = nil end def post(body=nil, &block) @post = Net::HTTP::Post.new(uri.path) @post["Content-type"] = "application/xml" @post.body = body File.new("./response/send_post", "w").write body @res = send @post @result = yield @res.body if block_given? end def get(query={}, &block) fullPath = path_combine query @get = Net::HTTP::Get.new(fullPath) @res = send @get File.new("./response/tmp_GetCapability", "w").write @res.body @result = yield @res.body if block_given? end private def uri URI(@uri) end def path_combine(query={}) params = URI.encode_www_form(query) [uri.path, params].join('?') end def send(action) @packet.request( action ) end end # xml = '<?xml version="1.0" encoding="UTF-8"?> # <GetObservation service="SOS" version="2.0.0" xmlns="http://www.opengis.net/sos/2.0" xmlns:wsa="http://www.w3.org/2005/08/addressing" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:swe="http://www.opengis.net/swe/2.0" xmlns:swes="http://www.opengis.net/swes/2.0" xmlns:fes="http://www.opengis.net/fes/2.0" xmlns:gml="http://www.opengis.net/gml/32" xmlns:ogc="http://www.opengis.net/ogc" xmlns:om="http://www.opengis.net/om/1.0" xsi:schemaLocation="http://www.w3.org/2003/05/soap-envelope http://www.w3.org/2003/05/soap-envelope/soap-envelope.xsd http://www.opengis.net/sos/2.0 http://schemas.opengis.net/sos/2.0/sos.xsd"> # <procedure>urn:ogc:object:feature:Sensor:SWCB:sensor鳳義坑</procedure> # <offering>鳳義坑</offering> # <observedProperty>urn:ogc:def:phenomenon:OGC:1.0.30:rainfall_1day</observedProperty> # <responseFormat>application/json</responseFormat> # </GetObservation>'
class StopwatchController < ApplicationController before_action :set_stopwatch, only: [:update, :show] def create @stopwatch = Stopwatch.new(stopwatch_params) respond_to do |format| if @stopwatch.save format.json { render :show, status: :created, location: @stopwatch } else format.json { render json: @stopwatch.errors, status: :unprocessable_entity } end end end def update respond_to do |format| if @stopwatch.update(stopwatch_params) format.json { render :show, status: :ok, location: @stopwatch_params } else format.json { render json: @stopwatch_params.errors, status: :unprocessable_entity } end end end def show end private def set_stopwatch @stopwatch = Stopwatch.find(params[:id]) end def stopwatch_params params.require(:stopwatch).permit(:work_cyle, :fast_pause, :long_pause, :has_sound_on_terminate).merge(user_id: current_user.id) end end
require 'rails_helper' describe Message do describe '#create' do it "is valid with a content" do message = build(:message, image: nil) expect(message).to be_valid end it "is valid with a image" do message = build(:message, content: nil) expect(message).to be_valid end it "is valid with a content, image" do message = build(:message) expect(message).to be_valid end it "is invalid without a content, image" do message = build(:message, content: nil, image: nil,) message.valid? expect(message).not_to be_valid end it "is invalid without a group_id" do message = build(:message, group_id: nil) message.valid? expect(message).not_to be_valid end it "is invalid without a user_id" do message = build(:message, user_id: nil) message.valid? expect(message).not_to be_valid end end end
require "json" require "selenium-webdriver" require "test/unit" class LogIn < Test::Unit::TestCase def setup @driver = Selenium::WebDriver.for :chrome @base_url = "https://staging.shore.com/merchant/sign_in" @accept_next_alert = true @driver.manage.timeouts.implicit_wait = 30 @verification_errors = [] end def teardown @driver.quit assert_equal [], @verification_errors end def test_create_recurring_appt @driver.get "https://secure.shore.com/merchant/sign_in" @driver.find_element(:id, "merchant_account_email").clear @driver.find_element(:id, "merchant_account_email").send_keys "js@shore.com" @driver.find_element(:id, "merchant_account_password").clear @driver.find_element(:id, "merchant_account_password").send_keys "secret" @driver.find_element(:name, "button").click @driver.get "https://secure.shore.com/merchant/bookings?appshell=true&merchant_profile_id=2f475a27-162b-4994-857f-399d6acf25ea" sleep 3 checkbox = @driver.find_element(:css, "input#serviceStepsCheckbox"); if checkbox.selected? checkbox.click else @driver.find_element(:css, "div.service-steps-config > form.simple_form.form-horizontal > div.tile-footer > input.btn-blue").click end @driver.find_element(:css, "div.service-steps-config > form.simple_form.form-horizontal > div.tile-footer > input.btn-blue").click sleep 2 @driver.get "https://my.shore.com/calendar/week" sleep 5 #recurring week end after x appt sleep 2 @driver.find_element(:css, "div.as-Header-addActionsContainer > a").click sleep 2 @driver.find_element(:css, "div.as-Header-addActions > a:first-child").click sleep 2 @driver.find_element(:name, "customerSummary").click sleep 2 @driver.find_element(:css, "div.list-group.search-results > a:nth-of-type(1)").click sleep 2 @driver.find_element(:name, "subject").clear @driver.find_element(:name, "subject").send_keys "Automatic generated" @driver.find_element(:css, "div#asMain div:nth-child(3) > div:nth-child(2) > div > input:nth-child(1)").click sleep 3 @driver.find_element(:name, "showReccurrence").click sleep 3 @driver.find_element(:id, "recurrence-interval").clear @driver.find_element(:id, "recurrence-interval").send_keys "2" @driver.find_element(:css, "div.form-group.row > div:nth-of-type(2) > div > a > span:nth-of-type(1)").click @driver.find_element(:css, "ul > li:nth-of-type(2) > div").click @driver.find_element(:css, "div.form-group.row > div:nth-of-type(3) > div > a > span:nth-of-type(2)").click @driver.find_element(:css, "ul > li:nth-of-type(2) > div").click @driver.find_element(:id, "recurrence-count").clear @driver.find_element(:id, "recurrence-count").send_keys "6" @driver.find_element(:css, "button.btn.btn-primary").click sleep 2 @driver.find_element(:css, "div.panel-body > div:nth-of-type(4) > div > div.has-feedback > div > ul > li > input").send_keys "Afterburner" @driver.action.send_keys(:enter).perform @driver.find_element(:css, "div.panel-body > div:nth-of-type(5) > div > div.has-feedback > div > ul").click sleep 1 @driver.find_element(:css, "body > div:nth-of-type(8) > ul > li:first-child > div").click sleep 1 @driver.find_element(:css, "button.btn.btn-primary").click #recurring month never ending sleep 5 @driver.find_element(:css, "div.as-Header-addActionsContainer > a").click sleep 2 @driver.find_element(:css, "div.as-Header-addActions > a:first-child").click sleep 2 @driver.find_element(:name, "customerSummary").click sleep 2 @driver.find_element(:css, "div.list-group.search-results > a:nth-of-type(3)").click sleep 2 @driver.find_element(:name, "subject").clear @driver.find_element(:name, "subject").send_keys "Automatic generated" @driver.find_element(:css, "div#asMain div:nth-child(3) > div:nth-child(2) > div > input:nth-child(1)").click sleep 3 @driver.find_element(:name, "showReccurrence").click sleep 3 @driver.find_element(:id, "recurrence-interval").clear @driver.find_element(:id, "recurrence-interval").send_keys "2" @driver.find_element(:css, "div.form-group.row > div:nth-of-type(2) > div > a > span:nth-of-type(1)").click @driver.find_element(:css, "ul > li:nth-of-type(3) > div").click @driver.find_element(:css, "div.form-group.row > div:nth-of-type(3) > div > a > span:nth-of-type(2)").click @driver.find_element(:css, "ul > li:first-child > div").click @driver.find_element(:css, "button.btn.btn-primary").click sleep 2 @driver.find_element(:css, "div.panel-body > div:nth-of-type(4) > div > div.has-feedback > div > ul > li > input").send_keys "Afterburner" @driver.action.send_keys(:enter).perform @driver.find_element(:css, "div.panel-body > div:nth-of-type(5) > div > div.has-feedback > div > ul").click sleep 1 @driver.find_element(:css, "body > div:nth-of-type(8) > ul > li:first-child > div").click sleep 1 @driver.find_element(:css, "button.btn.btn-primary").click #recurring day ends on date sleep 5 @driver.find_element(:css, "div.as-Header-addActionsContainer > a").click sleep 2 @driver.find_element(:css, "div.as-Header-addActions > a:first-child").click sleep 2 @driver.find_element(:name, "customerSummary").click sleep 2 @driver.find_element(:css, "div.list-group.search-results > a:nth-of-type(2)").click sleep 2 @driver.find_element(:name, "subject").clear @driver.find_element(:name, "subject").send_keys "Automatic generated" @driver.find_element(:css, "div#asMain div:nth-child(3) > div:nth-child(2) > div > input:nth-child(1)").click sleep 3 @driver.find_element(:name, "showReccurrence").click sleep 3 @driver.find_element(:id, "recurrence-interval").clear @driver.find_element(:id, "recurrence-interval").send_keys "2" @driver.find_element(:css, "div.form-group.row > div:nth-of-type(2) > div > a > span:nth-of-type(1)").click @driver.find_element(:css, "ul > li:first-child > div").click @driver.find_element(:css, "div.form-group.row > div:nth-of-type(3) > div > a > span:nth-of-type(2)").click @driver.find_element(:css, "ul > li:nth-of-type(3) > div").click @driver.find_element(:id, "recurrence-ends-at").clear @driver.find_element(:id, "recurrence-ends-at").send_keys "11.11.2018" sleep 1 @driver.find_element(:css, "div#asMain div.widget-modal.modal-datepicker-template > div > div > div > div > div > table > tbody > tr:nth-child(4) > td:nth-child(5) > button[type=\"button\"]") sleep 1 @driver.action.send_keys(:enter).perform sleep 2 @driver.find_element(:css, "div.panel-body > div:nth-of-type(4) > div > div.has-feedback > div > ul > li > input").send_keys "Afterburner" @driver.action.send_keys(:enter).perform sleep 2 @driver.find_element(:css, "div.panel-body > div:nth-of-type(5) > div > div.has-feedback > div > ul > li > input").send_keys "T" @driver.action.send_keys(:enter).perform sleep 1 @driver.action.send_keys(:enter).perform end def verify(&blk) yield rescue Test::Unit::AssertionFailedError => ex @verification_errors << ex end end
module ClaimLossConcern extend ActiveSupport::Concern DEFAULT_COLUMN_WIDTH = 13.freeze CLAIM_LOSS_HEADERS = ['Claim Number', 'Claimant', 'DOI', 'Manual Number', 'Medical Paid', 'Comp Paid', 'MIRA Reserve', 'Total Cost', 'Subrogation', 'Non At Fault', 'HC', 'Code'].freeze module ClassMethods def claim_loss include InstanceMethods before_action :set_claim_loss_account, only: [:claim_loss_export, :ranged_claim_loss_export, :ranged_claim_loss_export_form] before_action :set_dates, only: [:claim_loss_export, :ranged_claim_loss_export, :ranged_claim_loss_export_form] before_action :prepare_claim_loss_data, only: [:claim_loss_export, :ranged_claim_loss_export_form] end end module InstanceMethods extend ActiveSupport::Concern def claim_loss_export generate_claim_loss_export end def ranged_claim_loss_export end def ranged_claim_loss_export_form @account.errors.add(:start_date, 'Start Date is required!') if claim_account_params[:start_date].blank? @account.errors.add(:end_date, 'End Date is required!') if claim_account_params[:end_date].blank? @account.errors.add(:start_date, 'Start Date cannot be after End Date!') if @start_date.present? && @end_date.present? && @start_date > @end_date if @account.errors.any? flash[:danger] = 'Something went wrong, please try again!' render :ranged_claim_loss_export else generate_claim_loss_export end end private def claim_account_params params.require(:account).permit(:group_rating_id, :start_date, :end_date) end def set_claim_loss_account @account = Account.find_by(id: params[:account_id] || params[:id]) redirect_to page_not_found_path and return unless @account.present? @group_rating = GroupRating.find_by(id: params[:group_rating_id] || claim_account_params[:group_rating_id]) @representative = @account.representative @policy_calculation = @account.policy_calculation redirect_to page_not_found_path unless @policy_calculation.present? end def set_dates if params[:account].present? && claim_account_params[:start_date].present? && claim_account_params[:end_date].present? @start_date = Date.parse(claim_account_params[:start_date]) @end_date = Date.parse(claim_account_params[:end_date]) @experience_only = true else @start_date = @group_rating.experience_period_lower_date @end_date = @group_rating.experience_period_upper_date @experience_only = false if @policy_calculation.public_employer? @start_date = (@start_date + 1.year).beginning_of_year @end_date = @end_date.end_of_year end end end def generate_claim_loss_export require 'rubyXL' require 'rubyXL/convenience_methods' # Create workbook @claim_loss_workbook = RubyXL::Workbook.new if @experience_only @worksheet = @claim_loss_workbook.worksheets[0] @worksheet.sheet_name = 'Experience' experience_worksheet else @worksheet = @claim_loss_workbook.worksheets[0] @worksheet.sheet_name = 'Out of Experience' out_of_experience_worksheet @worksheet = @claim_loss_workbook.add_worksheet("Experience") experience_worksheet @worksheet = @claim_loss_workbook.add_worksheet("Green Year Experience") green_year_experience_worksheet end # Set font size of whole file @claim_loss_workbook.worksheets.each(&method(:check_column_widths)) send_data @claim_loss_workbook.stream.string, filename: "#{@account.name.parameterize.underscore}_claim_loss.xlsx", disposition: :attachment end def prepare_claim_loss_data # Logic should be the same as risk report for claim loss if @experience_only init_ranged_experience_data else init_experience_data init_out_of_experience_data init_ten_year_experience_data init_green_year_experience_data end end def init_ranged_experience_data # Experience Years Parameters first_experience_year = @start_date.strftime("%Y").to_i first_experience_year_period = @start_date..(@start_date.advance(years: 1).advance(days: -1)) first_experience_year_claims = @account.policy_calculation.claim_calculations.where("claim_injury_date BETWEEN ? AND ? ", first_experience_year_period.first, first_experience_year_period.last).order(:claim_injury_date) @experience_only_years = [first_experience_year] @experience_only_years_claims = [first_experience_year_claims] year_experience_period = first_experience_year_period experience_year = first_experience_year until year_experience_period.last.advance(days: 1) > @end_date experience_year += 1 year_experience_period = year_experience_period.last.advance(days: 1)..[year_experience_period.last.advance(years: 1), @end_date].min @experience_only_years << experience_year @experience_only_years_claims << @account.policy_calculation.claim_calculations.where("claim_injury_date BETWEEN ? AND ? ", year_experience_period.first, year_experience_period.last).order(:claim_injury_date) end experience_total_data end def init_experience_data @first_experience_year = @start_date.strftime("%Y").to_i @first_experience_year_period = @start_date..(@start_date.advance(years: 1).advance(days: -1)) @first_experience_year_claims = @account.policy_calculation.claim_calculations.where("claim_injury_date BETWEEN ? AND ? ", @first_experience_year_period.first, @first_experience_year_period.last).order(:claim_injury_date) @second_experience_year = @first_experience_year + 1 @second_experience_year_period = @first_experience_year_period.last.advance(days: 1)..@first_experience_year_period.last.advance(years: 1) @second_experience_year_claims = @account.policy_calculation.claim_calculations.where("claim_injury_date BETWEEN ? AND ? ", @second_experience_year_period.first, @second_experience_year_period.last).order(:claim_injury_date) @third_experience_year = @second_experience_year + 1 @third_experience_year_period = @second_experience_year_period.first.advance(years: 1)..@second_experience_year_period.last.advance(years: 1) @third_experience_year_claims = @account.policy_calculation.claim_calculations.where("claim_injury_date BETWEEN ? AND ? ", @third_experience_year_period.first, @third_experience_year_period.last).order(:claim_injury_date) @fourth_experience_year = @third_experience_year + 1 @fourth_experience_year_period = @third_experience_year_period.first.advance(years: 1)..@third_experience_year_period.last.advance(years: 1) @fourth_experience_year_claims = @account.policy_calculation.claim_calculations.where("claim_injury_date BETWEEN ? AND ? ", @fourth_experience_year_period.first, @fourth_experience_year_period.last).order(:claim_injury_date) experience_total_data end def init_out_of_experience_data # Out Of Experience Years Parameters @first_out_of_experience_year = @first_experience_year - 5 @first_out_of_experience_year_period = @first_experience_year_period.first.advance(years: -5)..@first_experience_year_period.last.advance(years: -5) @first_out_of_experience_year_claims = @account.policy_calculation.claim_calculations.where("claim_injury_date BETWEEN ? AND ? ", @first_out_of_experience_year_period.first, @first_out_of_experience_year_period.last).order(:claim_injury_date) @second_out_of_experience_year = @first_experience_year - 4 @second_out_of_experience_year_period = @first_experience_year_period.first.advance(years: -4)..@first_experience_year_period.last.advance(years: -4) @second_out_of_experience_year_claims = @account.policy_calculation.claim_calculations.where("claim_injury_date BETWEEN ? AND ? ", @second_out_of_experience_year_period.first, @second_out_of_experience_year_period.last).order(:claim_injury_date) @third_out_of_experience_year = @first_experience_year - 3 @third_out_of_experience_year_period = @first_experience_year_period.first.advance(years: -3)..@first_experience_year_period.last.advance(years: -3) @third_out_of_experience_year_claims = @account.policy_calculation.claim_calculations.where("claim_injury_date BETWEEN ? AND ? ", @third_out_of_experience_year_period.first, @third_out_of_experience_year_period.last).order(:claim_injury_date) @fourth_out_of_experience_year = @first_experience_year - 2 @fourth_out_of_experience_year_period = @first_experience_year_period.first.advance(years: -2)..@first_experience_year_period.last.advance(years: -2) @fourth_out_of_experience_year_claims = @account.policy_calculation.claim_calculations.where("claim_injury_date BETWEEN ? AND ? ", @fourth_out_of_experience_year_period.first, @fourth_out_of_experience_year_period.last).order(:claim_injury_date) @fifth_out_of_experience_year = @first_experience_year - 1 @fifth_out_of_experience_year_period = @first_experience_year_period.first.advance(years: -1)..@first_experience_year_period.last.advance(years: -1) @fifth_out_of_experience_year_claims = @account.policy_calculation.claim_calculations.where("claim_injury_date BETWEEN ? AND ? ", @fifth_out_of_experience_year_period.first, @fifth_out_of_experience_year_period.last).order(:claim_injury_date) # Out Of Experience Totals @out_of_experience_year_claims = @account.policy_calculation.claim_calculations.where("claim_injury_date BETWEEN ? AND ? ", @first_out_of_experience_year_period.first, @fifth_out_of_experience_year_period.last).order(:claim_injury_date) @out_of_experience_med_only = @out_of_experience_year_claims.where("left(claim_type, 1) = '1'").count @out_of_experience_lost_time = @out_of_experience_year_claims.where("left(claim_type, 1) = '2'").count @out_of_experience_comp_total = 0 @out_of_experience_medical_total = 0 @out_of_experience_mira_medical_reserve_total = 0 @out_of_experience_year_claims.each do |e| if e.claim_handicap_percent.present? && e.claim_subrogation_percent.present? && e.claim_group_multiplier.present? @out_of_experience_comp_total += (((e.claim_mira_reducible_indemnity_paid + e.claim_mira_non_reducible_indemnity_paid) * (1 - e.claim_subrogation_percent) - (e.claim_mira_non_reducible_indemnity_paid)) * (1 - e.claim_handicap_percent) + (e.claim_mira_non_reducible_indemnity_paid)) * e.claim_group_multiplier @out_of_experience_medical_total += (((e.claim_medical_paid + e.claim_mira_non_reducible_indemnity_paid_2) * (1 - e.claim_subrogation_percent) - e.claim_mira_non_reducible_indemnity_paid_2) * (1 - e.claim_handicap_percent) + e.claim_mira_non_reducible_indemnity_paid_2) * e.claim_group_multiplier @out_of_experience_mira_medical_reserve_total += (1 - e.claim_handicap_percent) * (e.claim_mira_medical_reserve_amount + (e.claim_mira_indemnity_reserve_amount)) * e.claim_group_multiplier * (1 - e.claim_subrogation_percent) end end @out_of_experience_group_modified_losses_total = @out_of_experience_year_claims.sum(:claim_modified_losses_group_reduced) @out_of_experience_individual_modified_losses_total = @out_of_experience_year_claims.sum(:claim_modified_losses_individual_reduced) @out_of_experience_individual_reduced_total = @out_of_experience_year_claims.sum(:claim_individual_reduced_amount) @out_of_experience_subrogation_total = @out_of_experience_year_claims.sum(:claim_total_subrogation_collected) @out_of_experience_si_total = @out_of_experience_year_claims.sum(:claim_unlimited_limited_loss) - @out_of_experience_year_claims.sum(:claim_total_subrogation_collected) @out_of_experience_year_totals = [round(@out_of_experience_medical_total, 0), round(@out_of_experience_comp_total, 0), round(@out_of_experience_mira_medical_reserve_total, 0), round(@out_of_experience_si_total, 0), round(@out_of_experience_subrogation_total, 0), '', '', ''] end def init_ten_year_experience_data # TEN YEAR EXPERIENCE TOTALS @ten_year_claims = @account.policy_calculation.claim_calculations.where("claim_injury_date BETWEEN ? AND ? ", @first_out_of_experience_year_period.first, @end_date).order(:claim_injury_date) @ten_year_med_only = @ten_year_claims.where("left(claim_type, 1) = '1'").count @ten_year_lost_time = @ten_year_claims.where("left(claim_type, 1) = '2'").count @ten_year_rc_01 = @ten_year_claims.where("left(claim_mira_ncci_injury_type, 1) = '01'").count @ten_year_rc_02 = @ten_year_claims.where("left(claim_mira_ncci_injury_type, 1) = '02'").count @ten_year_comp_total = (@ten_year_claims.sum(:claim_modified_losses_group_reduced) - @ten_year_claims.sum(:claim_medical_paid) - @ten_year_claims.sum(:claim_mira_medical_reserve_amount)) @ten_year_medical_total = @ten_year_claims.sum(:claim_medical_paid) @ten_year_mira_medical_reserve_total = @ten_year_claims.sum(:claim_mira_medical_reserve_amount) @ten_year_group_modified_losses_total = @ten_year_claims.sum(:claim_modified_losses_group_reduced) @ten_year_individual_modified_losses_total = @ten_year_claims.sum(:claim_modified_losses_individual_reduced) @ten_year_individual_reduced_total = @ten_year_claims.sum(:claim_individual_reduced_amount) @ten_year_subrogation_total = @ten_year_claims.sum(:claim_total_subrogation_collected) @ten_year_si_total = @experience_si_total + @out_of_experience_si_total @ten_year_si_avg = (@ten_year_si_total / 10) @ten_year_si_ratio_avg = 'N/A' @ten_year_si_average = (@ten_year_si_total / 10) @ten_year_si_ratio_avg = 'N/A' @ten_year_totals = [round(@ten_year_medical_total, 0), round(@ten_year_comp_total, 0), round(@ten_year_mira_medical_reserve_total, 0), round(@ten_year_si_total, 0), round(@ten_year_subrogation_total, 0), '', '', ''] end def init_green_year_experience_data # GREEN YEAR EXPERIENCE @first_green_year = @end_date.strftime("%Y").to_i @first_green_year_period = (@end_date.advance(days: 1))..(@end_date.advance(years: 1)) @first_green_year_claims = @account.policy_calculation.claim_calculations.where("claim_injury_date BETWEEN ? AND ? ", @first_green_year_period.first, @first_green_year_period.last).order(:claim_injury_date) @second_green_year = @first_green_year + 1 @second_green_year_period = @first_green_year_period.first.advance(years: 1)..@first_green_year_period.last.advance(years: 1) @second_green_year_claims = @account.policy_calculation.claim_calculations.where("claim_injury_date BETWEEN ? AND ? ", @second_green_year_period.first, @second_green_year_period.last).order(:claim_injury_date) # GREEN YEAR EXPERIENCE TOTALS @green_year_claims = @account.policy_calculation.claim_calculations.where("claim_injury_date BETWEEN ? AND ? ", @first_green_year_period.first, @second_green_year_period.last).order(:claim_injury_date) @green_year_med_only = @green_year_claims.where("left(claim_type, 1) = '1'").count @green_year_loss_time = @green_year_claims.where("left(claim_type, 1) = '2'").count @green_year_comp_total = (@green_year_claims.sum(:claim_modified_losses_group_reduced) - @green_year_claims.sum(:claim_medical_paid) - @green_year_claims.sum(:claim_mira_medical_reserve_amount)) @green_year_comp_total = 0 @green_year_medical_total = 0 @green_year_mira_medical_reserve_total = 0 @green_year_claims.each do |e| if e.claim_handicap_percent.present? && e.claim_subrogation_percent.present? && e.claim_group_multiplier.present? @green_year_comp_total += (((e.claim_mira_reducible_indemnity_paid + e.claim_mira_non_reducible_indemnity_paid) * (1 - e.claim_subrogation_percent) - (e.claim_mira_non_reducible_indemnity_paid)) * (1 - e.claim_handicap_percent) + (e.claim_mira_non_reducible_indemnity_paid)) * e.claim_group_multiplier @green_year_medical_total += (((e.claim_medical_paid + e.claim_mira_non_reducible_indemnity_paid_2) * (1 - e.claim_subrogation_percent) - e.claim_mira_non_reducible_indemnity_paid_2) * (1 - e.claim_handicap_percent) + e.claim_mira_non_reducible_indemnity_paid_2) * e.claim_group_multiplier @green_year_mira_medical_reserve_total += (1 - e.claim_handicap_percent) * (e.claim_mira_medical_reserve_amount + (e.claim_mira_indemnity_reserve_amount)) * e.claim_group_multiplier * (1 - e.claim_subrogation_percent) end end @green_year_group_modified_losses_total = @green_year_claims.sum(:claim_modified_losses_group_reduced) @green_year_individual_modified_losses_total = @green_year_claims.sum(:claim_modified_losses_individual_reduced) @green_year_individual_reduced_total = @green_year_claims.sum(:claim_individual_reduced_amount) @green_year_subrogation_total = @green_year_claims.sum(:claim_total_subrogation_collected) @green_year_experience_totals = [round(@green_year_medical_total, 0), round(@green_year_comp_total, 0), round(@green_year_mira_medical_reserve_total, 0), round(@green_year_individual_reduced_total, 0), round(@green_year_subrogation_total, 0), '', '', ''] end def experience_total_data @experience_year_claims = @account.policy_calculation.claim_calculations.where("claim_injury_date BETWEEN ? AND ? ", @start_date, @end_date).order(:claim_injury_date) @experience_med_only = @experience_year_claims.where("left(claim_type, 1) = '1'").count @experience_lost_time = @experience_year_claims.where("left(claim_type, 1) = '2'").count @experience_comp_total = 0 @experience_medical_total = 0 @experience_mira_medical_reserve_total = 0 @experience_year_claims.each do |e| @experience_comp_total += (((e.claim_mira_reducible_indemnity_paid + e.claim_mira_non_reducible_indemnity_paid) * (1 - (e.claim_subrogation_percent || 0.00)) - (e.claim_mira_non_reducible_indemnity_paid)) * (1 - e.claim_handicap_percent) + (e.claim_mira_non_reducible_indemnity_paid)) * (e.claim_group_multiplier || 1) @experience_medical_total += (((e.claim_medical_paid + e.claim_mira_non_reducible_indemnity_paid_2) * (1 - (e.claim_subrogation_percent || 0.00)) - e.claim_mira_non_reducible_indemnity_paid_2) * (1 - e.claim_handicap_percent) + e.claim_mira_non_reducible_indemnity_paid_2) * (e.claim_group_multiplier || 1) @experience_mira_medical_reserve_total += (1 - e.claim_handicap_percent) * (e.claim_mira_medical_reserve_amount + (e.claim_mira_indemnity_reserve_amount)) * (e.claim_group_multiplier || 1) * (1 - (e.claim_subrogation_percent || 0.00)) end @experience_group_modified_losses_total = @experience_year_claims.sum(:claim_modified_losses_group_reduced) @experience_individual_modified_losses_total = @experience_year_claims.sum(:claim_modified_losses_individual_reduced) @experience_individual_reduced_total = @experience_year_claims.sum(:claim_individual_reduced_amount) @experience_si_total = @experience_year_claims.sum(:claim_unlimited_limited_loss) - @experience_year_claims.sum(:claim_total_subrogation_collected) @experience_subrogation_total = @experience_year_claims.sum(:claim_total_subrogation_collected) @experience_si_avg = (@experience_si_total / 4) @experience_si_ratio_avg = (@experience_si_total / @policy_calculation.policy_total_four_year_payroll) * @policy_calculation.policy_total_current_payroll @experience_year_totals = [round(@experience_medical_total, 0), round(@experience_comp_total, 0), round(@experience_mira_medical_reserve_total, 0), round(@experience_si_total, 0), round(@experience_subrogation_total, 0), '', '', ''] end ## Worksheet Helpers def out_of_experience_worksheet new_worksheet_info injury_years_data([@first_out_of_experience_year, @second_out_of_experience_year, @third_out_of_experience_year, @fourth_out_of_experience_year, @fifth_out_of_experience_year], [@first_out_of_experience_year_claims, @second_out_of_experience_year_claims, @third_out_of_experience_year_claims, @fourth_out_of_experience_year_claims, @fifth_out_of_experience_year_claims]) experience_totals("Out Of Experience Year Totals", @out_of_experience_year_totals, @out_of_experience_med_only, @out_of_experience_lost_time) end def experience_worksheet new_worksheet_info if @experience_only injury_years_data(@experience_only_years, @experience_only_years_claims) else injury_years_data([@first_experience_year, @second_experience_year, @third_experience_year, @fourth_experience_year].compact, [@first_experience_year_claims, @second_experience_year_claims, @third_experience_year_claims, @fourth_experience_year_claims].compact) end experience_totals("Experience Year Totals", @experience_year_totals, @experience_med_only, @experience_lost_time) @current_row += 3 end def green_year_experience_worksheet new_worksheet_info injury_years_data([@first_green_year, @second_green_year], [@first_green_year_claims, @second_green_year_claims]) experience_totals("Green Year Experience Totals", @green_year_experience_totals, @green_year_med_only, @green_year_loss_time) end def new_worksheet_info @current_row = 0 insert_header insert_current_date end def insert_header @worksheet.merge_cells(@current_row, 0, @current_row, 3) @worksheet.change_row_bold(@current_row, true) @worksheet.add_cell(@current_row, 0, @representative.company_name.titleize) @current_row += 1 @worksheet.merge_cells(@current_row, 0, @current_row, 3) @worksheet.change_row_bold(@current_row, true) @worksheet.add_cell(@current_row, 0, @account.name.titleize) @current_row += 1 @worksheet.merge_cells(@current_row, 0, @current_row, 3) @worksheet.change_row_bold(@current_row, true) @worksheet.add_cell(@current_row, 0, "Policy Number: #{@policy_calculation.policy_number}") @current_row += 1 @worksheet.merge_cells(@current_row, 0, @current_row, 3) @worksheet.change_row_bold(@current_row, true) @worksheet.add_cell(@current_row, 0, "Date Range: #{@start_date.strftime('%m/%d/%Y')} - #{@end_date.strftime('%m/%d/%Y')}") @current_row += 3 end def insert_current_date @worksheet.add_cell(@current_row, 10, "Data Current As Of:") @worksheet.add_cell(@current_row, 11, Date.current.strftime('%m/%d/%Y')) end def check_column_widths(worksheet) max_column_index = worksheet.map { |row| row && row.cells.size || 0 }.max [*0..max_column_index].each do |column| column_width = DEFAULT_COLUMN_WIDTH worksheet.each_with_index do |_, row| next unless worksheet[row].present? cell = worksheet[row][column] next unless cell.present? worksheet.change_row_font_size(row, 12) worksheet.change_row_height(row, 16) worksheet.change_row_horizontal_alignment(row, :left) cell_width = (cell.value&.to_s&.size || 0) * 1.5 column_width = cell_width if cell_width > column_width end worksheet.change_column_width(column, column_width) end end def experience_totals(total_text, year_totals, med_only, lost_time) @worksheet.change_row_bold(@current_row, true) @worksheet.merge_cells(@current_row, 0, @current_row, 3) @worksheet.add_cell(@current_row, 0, total_text).change_horizontal_alignment(:center) [*0..year_totals.size - 1].each { |total_data_index| @worksheet.add_cell(@current_row, total_data_index + 4, year_totals[total_data_index]).change_border(:top, :medium) } @current_row += 2 @worksheet.change_row_bold(@current_row, true) @worksheet.add_cell(@current_row, 0, "Med Only Claim Count: #{med_only}") @current_row += 1 @worksheet.change_row_bold(@current_row, true) @worksheet.add_cell(@current_row, 0, "Lost Time Claim Count: #{lost_time}") @current_row += 1 end def injury_years_data(injury_years, injury_data) table_data = [] injury_data.each do |data| claims_data, total_data = claim_data(data) table_data << { data: claims_data, totals: total_data } end injury_years.each_with_index do |year, index| @worksheet.merge_cells(@current_row, 0, @current_row, 1) @worksheet.add_cell(@current_row, 0, "Injury Year: #{year}") @worksheet.change_row_bold(@current_row, true) year_data = table_data[index] @current_row += 2 CLAIM_LOSS_HEADERS.each_with_index do |header, column| @worksheet.add_cell(@current_row, column, header) @worksheet[@current_row][column].change_border(:bottom, :medium) @worksheet.change_row_bold(@current_row, true) end @current_row += 1 year_data[:data].each_with_index do |claim_data, row_index| [*0..CLAIM_LOSS_HEADERS.size].each_with_index do |column, column_index| @worksheet.add_cell(@current_row, column, claim_data[column]) @worksheet[@current_row][column_index - 1].change_border(:bottom, :medium) if row_index == year_data[:data].size - 1 end @current_row += 1 end @worksheet.change_row_bold(@current_row, true) @worksheet.merge_cells(@current_row, 0, @current_row, 3) @worksheet.add_cell(@current_row, 0, "Totals").change_horizontal_alignment(:center) [*0..year_data[:totals].size].each { |total_data_index| @worksheet.add_cell(@current_row, total_data_index + 4, year_data[:totals][total_data_index]) } @current_row += 3 end @worksheet.add_cell(@current_row, 0, '').change_border(:bottom, :medium) @worksheet.add_cell(@current_row, 1, '').change_border(:bottom, :medium) @worksheet.add_cell(@current_row, 2, '').change_border(:bottom, :medium) @worksheet.add_cell(@current_row, 3, '').change_border(:bottom, :medium) @current_row += 1 end def claim_data(claims_array) comp_total = 0 med_paid_total = 0 mira_res_total = 0 claims_array.each do |e| if e.claim_handicap_percent.present? && e.claim_subrogation_percent.present? && e.claim_group_multiplier.present? comp_total += (((e.claim_mira_reducible_indemnity_paid + e.claim_mira_non_reducible_indemnity_paid) * (1 - e.claim_subrogation_percent) - (e.claim_mira_non_reducible_indemnity_paid)) * (1 - e.claim_handicap_percent) + (e.claim_mira_non_reducible_indemnity_paid)) * e.claim_group_multiplier med_paid_total += (((e.claim_medical_paid + e.claim_mira_non_reducible_indemnity_paid_2) * (1 - e.claim_subrogation_percent) - e.claim_mira_non_reducible_indemnity_paid_2) * (1 - e.claim_handicap_percent) + e.claim_mira_non_reducible_indemnity_paid_2) * e.claim_group_multiplier mira_res_total += (1 - e.claim_handicap_percent) * (e.claim_mira_medical_reserve_amount + (e.claim_mira_indemnity_reserve_amount)) * e.claim_group_multiplier * (1 - e.claim_subrogation_percent) end end data = claims_array.map do |e| comp_awarded = "0" medical_paid = "0" mira_res = "0" if e.claim_handicap_percent.present? && e.claim_subrogation_percent.present? && e.claim_group_multiplier.present? comp_awarded = "#{round((((e.claim_mira_reducible_indemnity_paid + e.claim_mira_non_reducible_indemnity_paid) * (1 - e.claim_subrogation_percent) - (e.claim_mira_non_reducible_indemnity_paid)) * (1 - e.claim_handicap_percent) + (e.claim_mira_non_reducible_indemnity_paid)) * e.claim_group_multiplier, 0)}" medical_paid = "#{round((((e.claim_medical_paid + e.claim_mira_non_reducible_indemnity_paid_2) * (1 - e.claim_subrogation_percent) - e.claim_mira_non_reducible_indemnity_paid_2) * (1 - e.claim_handicap_percent) + e.claim_mira_non_reducible_indemnity_paid_2) * e.claim_group_multiplier, 0)}" mira_res = "#{round((1 - e.claim_handicap_percent) * (e.claim_mira_medical_reserve_amount + (e.claim_mira_indemnity_reserve_amount)) * e.claim_group_multiplier * (1 - e.claim_subrogation_percent), 0)}" end [e.claim_number, e.claimant_name.titleize, e.claim_injury_date.in_time_zone("America/New_York").strftime("%m/%d/%y"), e.claim_manual_number, medical_paid, comp_awarded, mira_res, round((e.claim_unlimited_limited_loss || 0) - (e.claim_total_subrogation_collected || 0), 0), round((e.claim_total_subrogation_collected || 0), 0), e.non_at_fault, percent(e.claim_handicap_percent), claim_code_calc(e)] end [data, [round(med_paid_total, 0), round(comp_total, 0), round(mira_res_total, 0), round(claims_array.sum(:claim_unlimited_limited_loss) - claims_array.sum(:claim_total_subrogation_collected), 0), round(claims_array.sum(:claim_total_subrogation_collected), 0), '', '', '']] end def price(num) view_context.number_to_currency(num) end def round(num, prec) view_context.number_with_precision(num, precision: prec, :delimiter => ',') end def rate(num, prec) if num.nil? return nil end num = num * 100 view_context.number_with_precision(num, precision: prec) end def percent(num) num = (num || 0) * 100 view_context.number_to_percentage(num, precision: 0) end def claim_code_calc(claim) claim_code = '' if claim.claim_type.present? && claim.claim_type[0] == '1' claim_code << "MO/" else claim_code << "LT/" end claim_code << claim.claim_status if claim.claim_status.present? claim_code << "/" claim_code << claim.claim_mira_ncci_injury_type if claim.claim_mira_ncci_injury_type.present? claim_code << "/NO COV" if claim.claim_type.present? && claim.claim_type[-1] == '1' claim_code end end end
class AddPlayerSeasons < ActiveRecord::Migration[5.2] def change create_table "player_seasons", force: :cascade do |t| t.integer :season t.references :player, foreign_key: true t.references :team, foreign_key: true t.references :roster, foreign_key: true end end end
module Ricer::Plug::Settings class IntegerSetting < Base def self.to_value(input) input.to_i rescue nil end def self.db_value(input) input.to_s end def self.to_label(input) input.to_s end def self.to_hint(options={}) I18n.t('ricer.plug.settings.hint.integer', min: min(options), max: max(options)) end def self.min(options) return options[:min] || 0 end def self.max(options) return options[:max] || 4123123123 end def self.is_valid?(input, options) return input != nil && input >= min(options) && input <= max(options) end end end
require "application_system_test_case" class StructureAnalysesTest < ApplicationSystemTestCase setup do @structure_analysis = structure_analyses(:one) end test "visiting the index" do visit structure_analyses_url assert_selector "h1", text: "Structure Analyses" end test "creating a Structure analysis" do visit structure_analyses_url click_on "New Structure Analysis" fill_in "Analysis", with: @structure_analysis.analysis_id fill_in "Price", with: @structure_analysis.price fill_in "Status", with: @structure_analysis.status fill_in "Structure", with: @structure_analysis.structure_id fill_in "User", with: @structure_analysis.user_id click_on "Create Structure analysis" assert_text "Structure analysis was successfully created" click_on "Back" end test "updating a Structure analysis" do visit structure_analyses_url click_on "Edit", match: :first fill_in "Analysis", with: @structure_analysis.analysis_id fill_in "Price", with: @structure_analysis.price fill_in "Status", with: @structure_analysis.status fill_in "Structure", with: @structure_analysis.structure_id fill_in "User", with: @structure_analysis.user_id click_on "Update Structure analysis" assert_text "Structure analysis was successfully updated" click_on "Back" end test "destroying a Structure analysis" do visit structure_analyses_url page.accept_confirm do click_on "Destroy", match: :first end assert_text "Structure analysis was successfully destroyed" end end
# frozen_string_literal: true require 'open-uri' require 'nokogiri' require './humantime' require './helpers' def add_human_time(item) stamp = item[:timestamp] item[:time_ago] = HumanTime.new(stamp) if stamp item end # Take a section of an XML file and traverse it in search of key, value pairs class ItemTraverser include RssAppHelpers def initialize(base, parts) @base = base @parts_list = parts end def collect item = @parts_list.each_with_object({}) do |(key, path), object| # Prefixed items can be a problem if they are not present begin @section = @base.xpath(path.first) rescue next end next if @section.empty? next object[key] = process_cdata(@section.children.to_s) if path.size == 1 @section.each do |cur| path[1].each do |element| key_name = "#{key}_#{element}".to_sym object[key_name] = process_cdata(cur[element]) end end end add_human_time(item) end end # Load and store a RSS / Atom feed. class Feed TOP_LEVEL = '//channel' ITEMS = '//item' INFO_PARTS = { title: ['title'], link: ['link'], description: ['description'], copyright: ['copyright'], image_url: ['image/url'], image_caption: ['image/title'], image_width: ['image/width'], image_height: ['image/height'], timestamp: ['lastBuildDate'] }.freeze ITEM_PARTS = { title: ['title'], description: ['description'], link: ['link'], timestamp: ['pubDate'], image: ['media:thumbnail', ['url']] }.freeze def initialize(feed_path) # This could be a file or web address. It could raise an exception. @rss = Nokogiri::XML open(feed_path) end def info @info ||= load_info end def items @items ||= load_items end def time_sorted_items items.sort_by { |item| Time.parse(item[:timestamp]) }.reverse end def title info[:title] end private def load_info info = @rss.xpath(TOP_LEVEL) ItemTraverser.new(info, INFO_PARTS).collect end def load_items @rss.xpath(ITEMS).each_with_object([]) do |item, array| array << ItemTraverser.new(item, ITEM_PARTS).collect end end end if $PROGRAM_NAME == __FILE__ require 'awesome_print' begin addr = ARGV[0] || 'bbc_rss_feed.xml' feed = Feed.new(addr) ap feed.info ap feed.items.size ap feed.items.take(5) rescue StandardError => e warn "Cannot open #{addr}: #{e}" end end
require 'spec_helper' RSpec.describe Aucklandia::Calendars do let(:client) { initialize_client } describe '#get_calendars' do context 'successful response' do it 'responds with a collection of calendars', vcr: true do response = client.get_calendars expect(response).to_not be_empty response.each do |calendar| expect(calendar).to include 'service_id', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday', 'start_date', 'end_date' end end end end end
class CreateSales < ActiveRecord::Migration def up create_table "sales" do |t| t.string "title" t.text "description" t.datetime "start" t.datetime "end" t.float "value" t.string "sale_type" t.datetime "created_at" t.datetime "updated_at" end end def down drop_table :sales end end
require 'spec_helper' module Alf describe Lispy, "Relation(...)" do let(:lispy){ Alf.lispy } subject{ lispy.Relation(*args) } describe 'on a single tuple' do let(:args){ [{:name => "Alf"}] } it{ should eq(Relation[*args]) } end describe 'on two tuples' do let(:args){ [{:name => "Alf"}, {:name => "Lispy"}] } it{ should eq(Relation[*args]) } end describe 'on a Symbol' do let(:args){ [:suppliers] } specify{ subject.should eq(lispy.environment.dataset(:suppliers).to_rel) } end describe "on the documentation example" do specify { lispy.evaluate{ Relation( Tuple(:pid => 'P1', :name => 'Nut', :color => 'red', :heavy => true ), Tuple(:pid => 'P2', :name => 'Bolt', :color => 'green', :heavy => false), Tuple(:pid => 'P3', :name => 'Screw', :color => 'blue', :heavy => false) ) }.should be_a(Relation) } end end end
class MoviesController < ApplicationController before_action :set_movie, only: [:show, :edit, :update, :destroy] load_and_authorize_resource # GET /movies # GET /movies.json def index @movies = Movie.all end def rate if current_user movie = Movie.find(params[:movie_id]) rating = current_user.user_ratings.where(movie_id: movie.id).first if rating rating.update_attributes(rating: params[:point]) else UserRating.create(rating: params[:point], user_id: current_user.id, movie_id: movie.id) end redirect_to movie else redirect_to movie_path(params[:movie_id]) end end def add_to_watchlist movie = Movie.find(params[:movie_id]) if WatchList.where(movie_id: movie.id, user_id: current_user.id).first redirect_to profile_path(current_user) else WatchList.create(movie_id: movie.id, user_id: current_user.id) redirect_to profile_path(current_user) end end def remove_from_watchlist movie = Movie.find(params[:movie_id]) WatchList.where(movie_id: movie.id, user_id: current_user.id).first.destroy redirect_to profile_path(current_user) end # GET /movies/1 # GET /movies/1.json def show @rating = UserRating.where(movie_id: @movie.id).average(:rating) if @rating @rating = @rating.round(1) else @rating = 0 end end # GET /movies/new def new @movie = Movie.new end # GET /movies/1/edit def edit end # POST /movies # POST /movies.json def create @movie = Movie.new(movie_params) respond_to do |format| if @movie.save movie_person_params[:actor_ids].each do |actor_id| MoviePerson.create(movie_id:@movie.id, person_id: actor_id, role: 'Actor') unless actor_id == '' end movie_person_params[:director_ids].each do |director_id| MoviePerson.create(movie_id:@movie.id, person_id: director_id, role: 'Director') unless director_id == '' end movie_person_params[:producer_ids].each do |producer_id| MoviePerson.create(movie_id:@movie.id, person_id: producer_id, role: 'Producer') unless producer_id == '' end movie_person_params[:writer_ids].each do |writer_id| MoviePerson.create(movie_id:@movie.id, person_id: writer_id, role: 'Writer') unless writer_id == '' end movie_person_params[:musician_ids].each do |musician_id| MoviePerson.create(movie_id:@movie.id, person_id: musician_id, role: 'Musician') unless musician_id == '' end format.html { redirect_to @movie, notice: 'Movie was successfully created.' } format.json { render :show, status: :created, location: @movie } else format.html { render :new } format.json { render json: @movie.errors, status: :unprocessable_entity } end end end # PATCH/PUT /movies/1 # PATCH/PUT /movies/1.json def update respond_to do |format| if @movie.update(movie_params) format.html { redirect_to @movie, notice: 'Movie was successfully updated.' } format.json { render :show, status: :ok, location: @movie } else format.html { render :edit } format.json { render json: @movie.errors, status: :unprocessable_entity } end end end # DELETE /movies/1 # DELETE /movies/1.json def destroy @movie.destroy respond_to do |format| format.html { redirect_to movies_url, notice: 'Movie was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_movie @movie = Movie.find(params[:id]) @comments = @movie.comments.all @comment = @movie.comments.build end # Never trust parameters from the scary internet, only allow the white list through. def movie_params params.require(:movie).permit(:title, :release_date, :plot, :cover, genre_ids: [], actor_ids: [], director_ids: []) end def movie_person_params params.require(:movie).permit(actor_ids: [], director_ids: [], producer_ids: [], writer_ids: [], musician_ids: []) end end
class Errors::BadRequest < GraphQL::ExecutionError def initialize super('リクエストが正しくありません') end def to_h super.merge('extensions' => { 'code' => 'Errors::BadRequest' }) end end
class ThoughtsController < ApplicationController before_action :authenticate_user! def index #include current user in the thoughts loop @my_friends = current_user.confirmed_friends_ids << current_user.id @thoughts = Thought.where(:user_id => @my_friends).all.order('created_at DESC') @thought = current_user.thoughts.build end def new @thought = current_user.thoughts.build end def create @thought = current_user.thoughts.build(thought_params) respond_to do |format| format.html { if @thought.save flash[:success] = 'Your thought has been published' redirect_to :back else flash[:warning] = 'There was a problem, try again later!' render 'new' end } format.js { @thought.save } end end def show @thought = Thought.find_by_id(params[:id]) @comment = Comment.new end def edit @thought = Thought.find_by_id(params[:id]) end def update @thought = Thought.find_by_id(params[:id]) if @thought.update_attributes(thought_params) flash[:success] = 'Thought updated!' redirect_to thought_path(@thought) else flash[:warning] = 'There was a problem' render 'edit' end end def destroy @thought = Thought.find_by_id(params[:id]) respond_to do |format| format.html { if @thought.destroy flash[:success] = 'Thought destroyed!' else flash[:warning] = 'There was a problem!' end redirect_to :back } format.js { @thought.destroy } end end private def thought_params params.require(:thought).permit(:content, :id) end end
class ConsultantExamInvitationsController < ApplicationController skip_load_and_authorize_resource def create authorize! :manage, :consultant_exam @user = User.find_by_id params[:user_id] return if create_has_error @user.create_sheet unless @user.answer_sheet message = validate_create_request ConsultantExamProcess.new(@user).invite_from(current_user) if message.key?(:success) redirect_to admin_user_path(@user), flash: message end private def validate_create_request return { error: _('User not found') } if @user.nil? return { error: _("You can't invite yourself") } if @user == current_user { success: _('Invitation sent') } end def create_has_error if @user == current_user flash[:error] = _("You can't invite yourself") redirect_to(request.referrer || '/', error: _("You can't invite yourself")) return true end unless @user flash[:error] = _('User not found') redirect_to(request.referrer || '/') return true end false end end
class Admin < ActiveRecord::Base has_secure_password validates :name, presence: true validates :name, uniqueness: true WEEKDAYS = %w[日 一 二 三 四 五 六] end
class AddSecAuthorToArticles < ActiveRecord::Migration def self.up add_column :articles, :author_sec_id, :integer add_index :articles, [:author_sec_id], :name => 'articles_author_sec_id_index' end def self.down remove_column :articles, :author_sec_id end end
# == Schema Information # # Table name: products # # id :integer not null, primary key # color :string # current_price :decimal(8, 2) # current_price_without_tax_reduction :decimal(8, 2) # description :text default("Beschreibung folgt") # fmid :integer # is_archived :boolean default(FALSE) # is_exclusive :boolean default(FALSE) # is_featured :boolean default(FALSE) # is_on_frontpage :boolean default(FALSE) # is_on_supersale :boolean default(FALSE) # is_published :boolean default(FALSE) # meta_description :text # name :string # official_description :text # orderable :boolean default(TRUE), not null # published_at :datetime # regular_price :decimal(8, 2) # sales_over_90_days :integer # sku :string # slug :string # use_in_lia_campaign :boolean default(FALSE) # created_at :datetime # updated_at :datetime # brand_id :bigint # size_id :integer # # Indexes # # index_products_on_brand_id (brand_id) # index_products_on_is_archived (is_archived) # index_products_on_is_exclusive (is_exclusive) # index_products_on_is_featured (is_featured) # index_products_on_is_on_frontpage (is_on_frontpage) # index_products_on_is_on_supersale (is_on_supersale) # index_products_on_is_published (is_published) # index_products_on_orderable (orderable) # index_products_on_published_at (published_at) # index_products_on_sales_over_90_days (sales_over_90_days) # index_products_on_size_id (size_id) # index_products_on_slug (slug) # index_products_on_use_in_lia_campaign (use_in_lia_campaign) # require 'test_helper' class ProductTest < ActiveSupport::TestCase setup do @product = products(:default_product) @hidden_product = products(:hidden_product) end test "product should have stock" do store_id = stores(:default_store).id size = "g8" assert @product.has_stock?(store: store_id, size: size), "Doesn't seem to be true" end test "product should not have stock" do store_id = stores(:default_store).id size = "g1" refute @product.has_stock?(store: store_id, size: size), "Doesn't seem to be false" end end
class InfoRegister::ArticleActivityRelation < ActiveRecord::Base belongs_to :article, :class_name => 'InfoRegister::Article' belongs_to :activity, :class_name => 'Admin::ReviewActivity' belongs_to :reviewer, :class_name => 'Admin::Person' end
class ProfilesController < ApplicationController before_filter :authenticate_user! inherit_resources defaults :singleton => true, :resource_class => User, :instance_name => 'user' actions :edit, :update, :show protected def resource @user ||= current_user end end
class ItemsController < ApplicationController before_action :authenticate_user! respond_to :html, :js def new @item = Item.new @list = current_user.lists.find(params[:list_id]) end def create @list = current_user.lists.find(params[:list_id]) @item = Item.new(params.require(:item).permit(:name)) @item.list_id = @list.id if @item.save redirect_to @list, :notice => "Your to-do was created." else render "new" end end def destroy @list = current_user.lists.find(params[:list_id]) @item = @list.items.find(params[:id]) if @item.destroy flash.now[:notice] = "Your task has been marked as complete" else flash.now[:error] = "There seemed to be an error, please try again" end respond_with(@item) do |format| format.html { redirect_to [@list] } # format.js { render :destroy } this is the default behaviour. end end end
require 'set' # Provides additional methods for Array. class Array # Returns true iff the array is not empty. def nonempty? return !empty? end end # Provides additional methods for Integer. class Integer # Returns true if the integer is a positive number. def positive? return self > 0 end # Returns true if the integer is not a positive number. def nonpositive? return self <= 0 end # Returns true if the integer is a negative number. def negative? return self < 0 end # Returns true if the integer is not a negative number. def nonnegative? return self >= 0 end end # Provides additional methods for String. class String # Set of all known positive responses. POSITIVE_RESPONSES = Set.new [ "ok", "okay", "sure", "y", "ye", "yeah", "yes" ] # Set of all known negative responses. NEGATIVE_RESPONSES = Set.new [ "n", "nah", "no", "nope" ] # Returns true iff the string is affirmative/positive. def is_positive? return POSITIVE_RESPONSES.include?(self) end # Returns true iff the string is negatory/negative. def is_negative? return NEGATIVE_RESPONSES.include?(self) end end
Sequel.migration do change do alter_table :calendars do add_column :label, String end alter_table :events do add_column :label, String end end end
class LikesController < ApplicationController before_action :set_variables , except: [:show] before_action :move_to_index , only: [:show] def like like = current_user.likes.new(cospul_id: @cospul.id) like.save end def unlike like = current_user.likes.find_by(cospul_id: @cospul.id) like.destroy end def show @likes = Like.where(user_id: "#{current_user.id}").pluck(:cospul_id) @cospuls = Cospul.where(id: @likes).new_posts.post_includes.set_page(params[:page]) end private def set_variables @cospul = Cospul.find(params[:cospul_id]) @id_name = "#like-link-#{@cospul.id}" end end
require 'spec_helper' RSpec.describe Stateoscope::Adapter::Base do describe '.handle?' do subject { described_class } it { is_expected.to have_abstract_method(:handle?) } end class Dummy; end describe '#initialize' do it 'initializes a graph' do adapter = described_class.new Dummy, "DummyState" expect(adapter.graph).to be_a(Stateoscope::Graph) end end describe '#build_graph' do subject { described_class.new(Dummy, "State") } it { is_expected.to have_abstract_method(:build_graph) } end describe '#full_state_machine_name' do subject { described_class.new(Dummy, "OK") } it { is_expected.to have_abstract_method(:full_state_machine_name) } end end
# frozen_string_literal: true module Riskified module Entities ## Reference: https://apiref.riskified.com/curl/#models-social Social = Riskified::Entities::KeywordStruct.new( #### Required ##### :network, :public_username, :account_url, :id, #### Optional ##### :community_score, :profile_picture, :email, :bio, :following, :followed, :posts, :auth_token, :social_data ) end end
class AddUrlToMeetupEvent < ActiveRecord::Migration def change add_column :meetup_events, :url, :string end end