text
stringlengths
10
2.61M
require 'models/exact_target_message' require 'mock_http_response' # This is used to redefine the ExactTargetMessage.do_http method to NOT query ET; instead # we load a response xml document that has already been set on the object class ExactTargetMessage def do_http(http, req) MockHttpResponse.new self.response || mock_error, '200', 'OK' end def mock_error <<-XML <?xml version="1.0" ?> <exacttarget> <system> <#{self.system_name.to_s}> <error>10000</error> <error_description>This is a hard coded mock error doc because you didn't specify a reponse yourself</error_description> </#{self.system_name.to_s}> </system> </exacttarget> XML end end
# == Schema Information # # Table name: blessings # # id :integer not null, primary key # location :string(255) # date :date # contactinfo :text # comments :text # created_at :datetime not null # updated_at :datetime not null # class Blessing < ActiveRecord::Base #allow creation of excel spreadsheet acts_as_xlsx attr_accessible :comments, :contactinfo, :date, :location, :chineseday, :chinesemonth, :chineseyear has_many :batches has_many :participants validates :location, presence: true # validates :validate_date validates_date :date#, :on_or_before => lambda { Date.current } def to_s self.location end def filenamefriendlylocation location.gsub(/ /, '') end def cchineseyear if self.chineseyear==nil "" else cnumbers=Setting.find_by_name("cnumbers").value.split(",") ccyear="" ccyear+=cnumbers[self.chineseyear/1000] ccyear+=cnumbers[self.chineseyear%1000/100] ccyear+=cnumbers[self.chineseyear%100/10] ccyear+=cnumbers[self.chineseyear%10] ccyear end end def cchinesemonth if self.chinesemonth==nil "" else cnumbers=Setting.find_by_name("cnumbers").value.split(",") ccmonth="" if(self.chinesemonth>9) ccmonth+=cnumbers[self.chinesemonth%100/10] + cnumbers[10] end ccmonth+=cnumbers[self.chinesemonth%10] ccmonth end end def cchineseday if self.chinesemonth==nil "" else cnumbers=Setting.find_by_name("cnumbers").value.split(",") ccday="" if(self.chineseday>9) ccday+=cnumbers[self.chineseday%100/10] + cnumbers[10] end ccday+=cnumbers[self.chineseday%10] ccday end end end
Puppet::Type.newtype(:fluffy_test) do @doc = 'Manage Fluffy test process for the current session' newparam(:name, :namevar => true) do desc 'Session name' newvalues(:puppet) end def refresh provider.test end end
module VotesHelper def link_to_vote(label, option) link_to(label, match_vote_path(option.match, :vote => {:option_id => option.id}), :method => :post, :class => 'btn-movie-vote') end def vote_percentage(match, option) percentage_value = (match.total_votes > 0) ? ((option.votes_count / match.total_votes.to_f) * 100) : 0 number_to_percentage(percentage_value, :precision => 0) end def vote_result_bar(match, option) div_class = 'votes-wrapper' div_class << ' winner' if (option.movie == match.winning_movie && match.ended?) content_tag(:div, :class => div_class) do content_tag(:div, :class => 'votes-bar', :style => "width: #{vote_percentage(match, option)}") do content_tag(:p, "#{pluralize(option.votes_count, 'vote')} - #{vote_percentage(match, option)}") end end end def current_users_match?(match) current_user == match.user end end
require 'erb' people = %w(yoko tomowo tim) # !> assigned but unused variable - people erb = ERB.new(<<-EOS,nil,'-') # !> Passing trim_mode with the 3rd argument of ERB.new is deprecated. Use keyword argument like ERB.new(str, trim_mode: ...) instead. <%- people.each do |person| %> * <%= person %> <%- end %> EOS erb.run binding # => nil # >> # >> * yoko # >> # >> * tomowo # >> # >> * tim # >>
require 'rails_helper' RSpec.describe CompulsoryRequirement, type: :model do before do q1 = FactoryGirl.create :qualification q2 = FactoryGirl.create :qualification s1 = FactoryGirl.create :skill s2 = FactoryGirl.create :skill j1 = FactoryGirl.create :job_type @requirement = FactoryGirl.create :requirement, :job_type_ids => [j1.id], :qualification_ids => [q1.id, q2.id], :skill_ids => [s1.id, s2.id] @compulsory_requirement = FactoryGirl.build :compulsory_requirement, requirement: @requirement end subject { @compulsory_requirement } @compulsory_requirement_attributes = [:requirement_id, :requirement_1, :requirement_2, :requirement_3, :requirement_4, :requirement_5, :requirement_6, :requirement_7, :requirement_8, :requirement_9, :requirement_10] @compulsory_requirement_attributes.each do |attribute| it { should respond_to attribute } end it { should belong_to :requirement } it { should be_valid } end
class ConfigVersion < ActiveRecord::Base has_many :jnlp validates_presence_of :key validates_uniqueness_of :key before_save :verify_valid_template def verify_valid_template begin # TODO how do we verify we have a valid template? # most templates will rely on externally set variables, which aren't going to be set here # so a straight eval won't work. Is there a way to parse it just to check if it's well-formed? # result = eval(self.template) rescue Exception => e raise "Invalid template #{e}" end end end
require 'json' require_relative 'rest_client' class GitHubClient COMMITS_URI = "https://api.github.com/repos/$1/$2/commits" COMMITTER_URI = "https://api.github.com/users/" def initialize(organization:, project:) @commit_uri = build_commit_uri(organization: organization, project: project) @rest_client = RestClient.new end def get_commits uri = URI(@commit_uri) response = @rest_client.get(uri) JSON.parse(response) end def get_committer(login: ) uri = COMMITTER_URI + login uri = URI(uri) response = @rest_client.get(uri) JSON.parse(response) end private def build_commit_uri(organization:, project:) COMMITS_URI.gsub("$1",organization).gsub("$2", project) end end #GitHubClient.get_commits #GitHubClient.get_committer(username: "vinirinaldis")
class Error class ValidationFailed < Error def initialize(data) super(:validation_failed, 400, data) end end end
require 'spec_helper' describe ReceptionsController do before(:each) do turn_of_devise_and_cancan_because_this_is_specced_in_the_ability_spec end specify { should have_devise_before_filter } def mock_reception(stubs={}) @mock_reception ||= mock_model(Reception, stubs) end describe "GET index" do it "assigns all receptions as @receptions" do Reception.stub(:find).with(:all).and_return([mock_reception]) get :index assigns[:receptions].should == [mock_reception] end end describe "GET show" do it "assigns the requested reception as @reception" do Reception.stub(:find).with("37").and_return(mock_reception) get :show, :id => "37" assigns[:reception].should equal(mock_reception) end end describe "POST create" do before(:each) do Reception.stub(:new).and_return(mock_reception) mock_reception.stub :organization_id= mock_reception.stub :delivery_id= mock_reception.stub :certificate= mock_reception.stub :content= end def post_create post :create, \ :delivery => delivery_params, :organization_id => mock_organization.to_param end def delivery_params { :id => mock_delivery.to_param, :message => 'CONTENT' } end describe "with valid params" do before(:each) do mock_reception.stub :save => true end it "assigns a newly created reception as @reception" do post_create assigns[:reception].should equal(mock_reception) end it "assigns the delivery hash to @reception.content" do mock_reception.should_receive(:content=).with('CONTENT') post_create end it "assigns the organization_id to @reception.organization_id" do mock_reception.should_receive(:organization_id=).with(mock_organization.to_param) post_create end it "assigns the delivery_id to @reception.delivery_id" do mock_reception.should_receive(:delivery_id=).with(mock_delivery.to_param) post_create end describe "in production mode" do before(:each) do Rails.env.stub :production? => true request.stub :ssl? => true end it "assigns the certificate from request.headers[SSL_CLIENT_CERT] to @reception.certificate" do request.env['SSL_CLIENT_CERT'] = 'CERTIFICATE' mock_reception.should_receive(:certificate=).with('CERTIFICATE') post_create end end describe "in development mode" do it "assigns a dummy certificate to @reception.certificate" do mock_reception.should_receive(:certificate=).with('NO CERTIFICATE') post_create end end it "redirects to the created reception" do post_create response.should redirect_to(reception_url(mock_reception)) end end describe "with invalid params" do before(:each) do mock_reception.stub :save => false end it "assigns a newly created but unsaved reception as @reception" do post_create assigns[:reception].should equal(mock_reception) end it "re-renders the 'new' template" do post_create response.should render_template('new') end end end end
class AddFieldsToOrders < ActiveRecord::Migration def change add_column :orders, :first_name, :string add_column :orders, :last_name, :string add_column :orders, :address, :string add_column :orders, :city, :string add_column :orders, :state, :string add_column :orders, :zipcode, :integer add_column :orders, :credit_card_number, :integer add_column :orders, :expiration_date, :string end end
class SpecimensController < ApplicationController before_action :set_work_order before_action :set_specimen, only: [:show, :edit, :update, :destroy] before_action :authorize_specimens, only: [:new, :create, :index] # GET /specimens def index if request.format.xls? @sheets = Specimen.where(sample_id: @work_order.samples.pluck(:id).flatten).to_xls else @page = params[:page] @per_page = 10 @specimens_filtered = params[:q].present? ? @work_order.specimens.by_name(params[:q]) : @work_order.specimens @specimens = @specimens_filtered.paginate page: params[:page], per_page: @per_page end # Display the data collected according to a format respond_to do |format| format.html format.json format.xls #format.csv { send_data @specimens.to_csv } end end # GET /specimens/1 def show end # GET /specimens/new def new @specimen = params["specimen"] ? Specimen.new(specimen_params) : Specimen.new @specimen_type_versions = SpecimenType.versions_for(@work_order) end # GET /specimens/1/edit def edit @specimen_type_versions = SpecimenType.versions_for(@work_order) end # POST /specimens def create @specimen = Specimen.new(specimen_params) # @specimen.work_order = @work_order if @specimen.save redirect_to [@work_order, @specimen] else @specimen_type_versions = SpecimenType.versions_for(@work_order) render :new end end # PATCH/PUT /specimens/1 def update if @specimen.update(specimen_params) redirect_to [@work_order, @specimen] else @specimen_type_versions = SpecimenType.versions_for(@work_order) render :edit end end # DELETE /specimens/1 def destroy if @specimen.destroy redirect_to specimens_url else render :show end end private # Use callbacks to share common setup or constraints between actions. def set_work_order @work_order = WorkOrder.find(params[:work_order_id]) authorize @work_order end def set_specimen @specimen = Specimen.find(params[:id]) authorize @specimen end # Authorization for class. def authorize_specimens authorize Specimen end # Only allow a trusted parameter "white list" through. def specimen_params params.require(:specimen).permit(:code, :remarks, :sample_id, :specimen_type_id, :specimen_type_version_id, :prepared_by_id, :data, pictures_attributes: [ :id, :local_id, :image, :_destroy]) end end
module DasParse def initialize( machine ) @machine = machine end def machine=(m) @machine=m end def machine @machine end def parse( text ) text = text.join if text.is_a?(Array) #puts "t0",text.inspect #text_no_comments = text.gsub( /\/\*[\s\S]*?\*\/|([^:]|^)\/\/.*$/,"" ) #text_no_comments = text.gsub( /\/\*[\s\S]+?\*\/|([^:]|^)\/\/.*$/,"" ) # заменил * на плюсик - чтобы хоть что-то было между /* */, так надо для инклюда а то пути вида lib/**/some считаются их куски за комменты.. parts = text.split(/^##+(?=[^#])/) # наелись https://stackoverflow.com/a/18089658 # а конкретно добавил скобочки и ?= чтобы после ### не сжирался сивмол # раньше было /^##+[^#]/ #итак у нас есть parts - это список записей #каждая запись это текст #первая строка (до \n) это инфа по заголовку, дальше тело # теперичо это надо обработать for p in parts do k = p.index("\n") || -1 next if k.nil? # пустые строчки name = p[0..k].strip value = (p[k..-1] || "").strip next if name.length == 0 # feature #@machine.log "calling process_record name=#{name} value=#{value}" process_record( name,value ) end end def process_record( title, value ) puts "warning! this is just p1_main debug message. why are you here?" puts "title=",title,"value=",value end def machine @machine end end LetterParser.prepend DasParse
class Project < ApplicationRecord enum status: [:created, :started, :stopped, :completed] belongs_to :user has_many :comments, :dependent => :destroy validates :name, :description, :estimated_effort, :actual_effort, :status, presence: true validates_inclusion_of :is_public, :in => [true, false] validates_inclusion_of :estimated_effort, :actual_effort, :in => 1..10 validates_numericality_of :estimated_effort, :actual_effort, only_integer: true, :in => 1..10 after_destroy :broadcast_delete def broadcast_delete ActionCable.server.broadcast 'projects', response: 'deleted', id: id end end
class FillInStudentPhoneNumberFromOrder < ActiveRecord::Migration def change Student.joins(:order).each do |student| next unless student.order.present? student.update(phone_number: student.order.billing_phone) end end end
class CreateResourceAssets < ActiveRecord::Migration def change create_table :resource_assets do |t| t.references :resource t.references :asset t.integer :order t.timestamps end add_index :resource_assets, :resource_id add_index :resource_assets, :asset_id end end
require File.join( File.dirname( __FILE__ ), "..", "spec_helper" ) class Configurator describe Server do before :each do Configuration.stub!( :temporary_directory ).and_return( "/tmp/lucie" ) end context "initializing a client" do before :each do dpkg = mock( "dpkg" ) dpkg.stub!( :installed? ).and_return( true ) Dpkg.stub!( :new ).and_return( dpkg ) scm = mock( "scm" ) scm.stub!( :name ).and_return( "Mercurial" ) scm.stub!( :clone ) Scm.stub!( :from ).and_return( scm ) end it "should create a temporary directory to checkout configuration repository if not found" do FileTest.stub!( :exists? ).with( "/tmp/lucie/config" ).and_return( false ) Lucie::Utils.should_receive( :mkdir_p ).with( "/tmp/lucie/config", an_instance_of( Hash ) ) Server.new( "Mercurial" ).clone( "URL" ) end it "should not create a temporary directory to checkout configuration repository if found" do FileTest.stub!( :exists? ).with( "/tmp/lucie/config" ).and_return( true ) Lucie::Utils.should_not_receive( :mkdir_p ).with( "/tmp/lucie/config" ) Server.new( "Mercurial" ).clone( "URL" ) end end context "checking if backend SCM is installed" do before :each do @dpkg = mock( "dpkg" ) Dpkg.stub!( :new ).and_return( @dpkg ) end it "should not raise if the SCM is installed" do @dpkg.stub!( :installed? ).with( "mercurial" ).and_return( true ) lambda do Server.new( :mercurial ).__send__( :check_scm ) end.should_not raise_error end it "should raise if the SCM is not installed" do @dpkg.stub!( :installed? ).with( "mercurial" ).and_return( false ) lambda do Server.new( :mercurial ).__send__( :check_scm ) end.should raise_error( "Mercurial is not installed" ) end it "should do nothing if not using SCM" do lambda do @dpkg.stub!( :installed? ).with( "mercurial" ).and_return( true ) Server.new( "Mercurial" ).__send__( :check_scm ) end.should_not raise_error end end context "making a clone of configuration repository on Lucie server" do before :each do @url = "ssh://myrepos.org//lucie" @dpkg = mock( "dpkg" ) @dpkg.stub!( :installed? ).and_return( true ) Dpkg.stub!( :new ).and_return( @dpkg ) end it "should create a clone directory on the Lucie server" do mercurial = mock( "mercurial" ) mercurial.stub!( :name ).and_return( "Mercurial" ) Scm::Mercurial.stub!( :new ).and_return( mercurial ) target = File.join( Configuration.temporary_directory, "config", Configurator.repository_name_from( @url ) ) mercurial.should_receive( :clone ).with( @url, target ) Server.new( :mercurial ).clone @url end it "should raise if scm not specified" do lambda do Server.new.clone @url end.should raise_error( "scm is not specified" ) end end context "making a local clone of configuration repository" do it "should create a local clone directory on the Lucie server" do dpkg = mock( "dpkg" ) dpkg.stub!( :installed? ).and_return( true ) Dpkg.stub!( :new ).and_return( dpkg ) mercurial = mock( "mercurial" ) mercurial.stub!( :name ).and_return( "Mercurial" ) Scm::Mercurial.stub!( :new ).and_return( mercurial ) mercurial.should_receive( :is_a? ).with( Scm::Mercurial ).and_return( true ) mercurial.should_receive( :clone ).with( "ssh://DUMMY_SERVER_IP//tmp/lucie/config/http_myrepos.org_lucie", "/tmp/lucie/config/http_myrepos.org_lucie.local" ) Server.new( :mercurial ).clone_clone "http://myrepos.org//lucie", "DUMMY_SERVER_IP" end end context "updating configuration repository" do it "should update configuration repository" do dpkg = mock( "dpkg" ) dpkg.stub!( :installed? ).and_return( true ) Dpkg.stub!( :new ).and_return( dpkg ) mercurial = mock( "mercurial" ) mercurial.stub!( :name ).and_return( "Mercurial" ) Scm::Mercurial.stub!( :new ).and_return( mercurial ) mercurial.should_receive( :is_a? ).with( Scm::Mercurial ).and_return( true ) mercurial.should_receive( :update ).with( "/tmp/lucie/config/http_myrepos.org_lucie" ) mercurial.should_receive( :update ).with( "/tmp/lucie/config/http_myrepos.org_lucie.local" ) Server.new( :mercurial ).update Configurator.repository_name_from( "http://myrepos.org//lucie" ) end end end end ### Local variables: ### mode: Ruby ### coding: utf-8 ### indent-tabs-mode: nil ### End:
class ApplicationController < ActionController::Base include Pundit # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception rescue_from ActiveRecord::RecordNotFound, with: :record_not_found rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized before_action :configure_permitted_parameters, if: :devise_controller? helper_method :cart_session protected def record_not_found render 'pages/404', status: :not_found end def user_not_authorized flash[:alert] = "Você não tem permissão para fazer isso." redirect_to(request.referrer || root_path) end def store_location store_location_for(:user, request.path) end def cart_session @cart_session ||= CartSession.new(session) end def configure_permitted_parameters parameters = %i( address cpf current_password email name password password_confirmation phone ) devise_parameter_sanitizer.for(:sign_up) do |user| user.permit(*parameters) end devise_parameter_sanitizer.for(:account_update) do |user| user.permit(*parameters) end end end
class AddReferencesToBandMembers < ActiveRecord::Migration[5.2] def change add_reference :band_members, :band, foreign_key: true add_reference :band_members, :musician, foreign_key: true end end
class InitialSchema < ActiveRecord::Migration[5.2] create_table "boxscores", force: :cascade do |t| t.string "name", limit: 255 t.date "date" t.integer "season", limit: 4 t.string "ballpark", limit: 255 t.integer "home_team_id", limit: 4 t.integer "away_team_id", limit: 4 t.integer "winning_team_id", limit: 4 t.integer "home_runs", limit: 4 t.integer "away_runs", limit: 4 t.integer "total_innings", limit: 4 t.text "stats", limit: 65535 t.text "content", limit: 65535 end add_index "boxscores", ["name", "season"], name: "name_ndx", unique: true add_index "boxscores", ["date"], name: "boxscore_date_ndx", unique: false add_index "boxscores", ["season"], name: "boxscore_season_ndx", unique: false create_table "games", force: :cascade do |t| t.integer "boxscore_id", limit: 4 t.date "date" t.integer "season", limit: 4 t.boolean "home" t.integer "team_id", limit: 4 t.integer "opponent_id", limit: 4 t.boolean "win" t.integer "runs", limit: 4 t.integer "opponent_runs", limit: 4 t.integer "total_innings", limit: 4 end add_index "games", ["boxscore_id","home"], name: "boxscore_game_ndx", unique: true add_index "games", ["team_id", "opponent_id", "win"], name: "team_win_ndx" add_index "games", ["date"], name: "game_date_ndx", unique: false add_index "games", ["season"], name: "game_season_ndx", unique: false create_table "innings", force: :cascade do |t| t.integer "boxscore_id", limit: 4 t.integer "season", limit: 4 t.integer "team_id", limit: 4 t.integer "inning", limit: 4 t.integer "runs", limit: 4 t.integer "opponent_runs", limit: 4 end add_index "innings", ["boxscore_id", "team_id", "inning"], name: "innings_ndx", unique: true create_table "owners", force: :cascade do |t| t.string "uid", limit: 255, default: "", null: false t.string "firstname", limit: 255, default: "", null: false t.string "lastname", limit: 255, default: "", null: false t.string "nickname", limit: 255, default: "", null: false t.string "email", limit: 255, default: "", null: false t.string "token", limit: 40 t.boolean "is_admin", default: false t.datetime "last_login_at" t.integer "primary_owner_id", limit: 4 t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "owners", ["email"], name: "index_owners_on_email", unique: true create_table "records", force: :cascade do |t| t.date "date" t.integer "season", limit: 4 t.integer "games", limit: 4 t.integer "team_id", limit: 4 t.integer "wins", limit: 4 t.integer "losses", limit: 4 t.integer "wins_minus_losses", limit: 4 t.integer "rf", limit: 4 t.integer "ra", limit: 4 t.float "gb", limit: 24 t.string "streak", limit: 255 t.integer "home_games", limit: 4 t.integer "home_wins", limit: 4 t.integer "road_games", limit: 4 t.integer "road_wins", limit: 4 t.integer "home_rf", limit: 4 t.integer "home_ra", limit: 4 t.integer "road_rf", limit: 4 t.integer "road_ra", limit: 4 end add_index "records", ["date", "season", "team_id"], name: "records_ndx", unique: true create_table "teams", force: :cascade do |t| t.integer "owner_id", limit: 4 t.string "name", limit: 255, default: "", null: false t.string "abbrev", limit: 3, default: "", null: false t.string "league", limit: 10, default: "", null: false t.string "division", limit: 4, default: "", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "teams", ["name"], name: "index_teams_on_name", unique: true create_table :uploads do |t| t.references :owner t.attachment :archivefile t.string :archivefile_fingerprint t.integer :processing_status, default: 0 t.integer :rebuild_id, null: true t.timestamps end add_index "uploads", ["archivefile_fingerprint"], name: "fingerprint_ndx", unique: true end
require 'open-uri' require 'yaml' module OmniFocus::Github VERSION = '1.0.0' GH_URL = "http://github.com" def fetch url, key base_url = "#{GH_URL}/api/v2/yaml" YAML.load(URI.parse("#{base_url}/#{url}").read)[key] end def populate_github_tasks user = `git config --global github.user`.chomp projects = fetch("repos/show/#{user}", "repositories").select { |project| project[:open_issues] > 0 }.map { |project| project[:name] } projects.sort.each do |project| fetch("issues/list/#{user}/#{project}/open", "issues").each do |issue| number = issue["number"] ticket_id = "GH-#{project}##{number}" title = "#{ticket_id}: #{issue["title"]}" url = "#{GH_URL}/#{user}/#{project}/issues/#issue/#{number}" if existing[ticket_id] then bug_db[existing[ticket_id]][ticket_id] = true next end bug_db[project][ticket_id] = [title, url] end end end end
Given(/^I am on the Google homepage$/) do visit 'https://google.co.uk' end When(/^I search for Ada Lovelace$/) do fill_in 'q', :with => 'Ada Lovelace' sleep 5 click_on(class: 'lsb', text: 'Google Search') end Then(/^I should see a Wikipedia link$/) do expect(page).to have_content('Wikipedia') end Given("I am on the Ada Lovelace results page") do visit 'https://www.google.co.uk/search?q=ada+lovelace&oq=ada+lovelace&aqs=chrome..69i57j0l5.2980j0j8&sourceid=chrome&ie=UTF-8' end Then("I should see the correct Ada Lovelace image") do expect(page).to have_css('#uid_dimg_0') end When("I select the Wikipedia link") do click_link('Ada Lovelace - Wikipedia') end Then("I should be taken to the expected page") do page.has_xpath?('/html/body/a') end
class CreateStructure < ActiveRecord::Migration def self.up create_table :projects do |t| t.string :name t.text :desc t.integer :owner_id t.timestamps end create_table :repositories do |t| t.string :name t.string :path t.integer :owner_id t.integer :repository_id t.timestamps end create_table :branches do |t| t.string :name t.integer :repository_id t.integer :owner_id t.timestamps end create_table :commits do |t| t.string :sha t.text :log t.integer :branch_id t.integer :author_id t.string :author_name t.timestamps end create_table :bugs do |t| t.string :title t.text :desc t.integer :repository_id t.integer :branch_id t.string :state t.timestamps end create_table :users do |t| t.string :login t.string :password t.string :email end create_table :talks do |t| t.string :title t.text :text t.integer :parent_id, :default => 0 t.integer :bug_id t.integer :commit_id t.string :action t.string :author_id t.timestamps end create_table :projects_users, :id => false do |t| t.integer :project_id t.integer :user_id end end def self.down drop_table :projects drop_table :repositories drop_table :branches drop_table :commits drop_table :bugs drop_table :users drop_table :projects_users drop_table :talks end end
require 'spec_helper' describe "counteroffers/show" do before(:each) do @counteroffer = assign(:counteroffer, stub_model(Counteroffer, :offer => nil, :buyer => "Buyer", :seller => "Seller", :buyer_price => "Buyer Price", :seller_price => "Seller Price" )) end it "renders attributes in <p>" do render # Run the generator again with the --webrat flag if you want to use webrat matchers rendered.should match(//) rendered.should match(/Buyer/) rendered.should match(/Seller/) rendered.should match(/Buyer Price/) rendered.should match(/Seller Price/) end end
# encoding: utf-8 ## # Facebook Open Graphic Protocol Service # class FacebookOgpService def post_topic(user_id, topic_id, topic_url) @user_id = user_id # TODO: check permission here ogp { |p| p.put_connections("me", "mongolian_rubyist:create", topic: topic_url) } end handle_asynchronously :post_topic, run_at: Proc.new { 10.seconds.from_now } def post_on_wall(user_id, topic_id, topic_url) @user_id = user_id # TODO: check permission here fb_post = Ogp::Facebook::WallPost.new(topic, topic_url) ogp { |p| p.put_wall_post("Би MORU дээр яригдах \"#{topic.title}\" сэдэвт санал өглөө.", fb_post.to_hash) } end handle_asynchronously :post_on_wall private def ogp @ogp ||= Koala::Facebook::API.new(user.try(:get_facebook_token)) block_given? ? yield(@ogp) : @ogp rescue Koala::Facebook::APIError => e Rails.logger.info e.to_s nil end def user @user ||= User.find(@user_id).extend OgpContext end def topic(id) @topic ||= Topic.find(id) end end
class Customer::CartItemsController < ApplicationController before_action :authenticate_customer! def index @cart_item = CartItem.where(customer_id: current_customer.id).order("created_at DESC") end def update @cart_item = CartItem.find(params[:id]) @cart_items = CartItem.where(customer_id: current_customer.id).order("created_at DESC") if @cart_item.update(cart_item_params) flash[:success] = "個数を変更しました" redirect_to cart_items_path else flash[:danger] = "正しい個数を入力してください" redirect_to cart_items_path end end def destroy @cart_item = CartItem.find(params[:id]) @cart_items = CartItem.where(customer_id: current_customer.id).order("created_at DESC") @cart_item.destroy flash[:success] = "選択した商品を削除しました" redirect_to cart_items_path end def all_delete @cart_items = current_customer.cart_items.all @cart_items.destroy_all flash[:success] = "カートが空になりました" redirect_to cart_items_path end def create @cart_items = CartItem.find_by(customer_id: current_customer.id, item_id: params[:cart_item][:item_id]) if @cart_items.present? @cart_items.amount += params[:cart_item][:amount].to_i @cart_items.save flash[:success] = "カートに追加しました" redirect_to cart_items_path else @cart_item = CartItem.new(cart_item_params) @cart_item.customer_id = current_customer.id if @cart_item.save flash[:success] = "カートに追加しました" redirect_to cart_items_path else flash[:danger] = "個数を入力してください" redirect_to item_path(@cart_item.item) end end end # Strong parameters private def cart_item_params params.require(:cart_item).permit(:item_id, :amount) end end
module Enumerable def group_by inject({}) do |h, e| h.fetch(yield(e)) { |k| h[k] = [] } << e; h end end unless method_defined?(:group_by) end
module SemanticNavigation module Core module MixIn module DslMethods def item(id, url=nil, options={}, &block) options[:id] = id.to_sym options[:render_if] = [*@render_if, options[:render_if], *@scope_render_if].compact if url.is_a?(Array) options[:url] = [url].flatten(1).map{|url| scope_url_params(decode_url(url))} else options[:url] = scope_url_params(decode_url(url)) end options[:i18n_name] = @i18n_name if block_given? element = Node.new(options, @level+1) element.instance_eval &block else element = Leaf.new(options, @level+1) #Deprecation warning message #TODO:Should be deleted after moving the header and divider definition via item if element.url.nil? && !element.name.empty? SemanticNavigation.deprecation_message(:method, 'item', 'header', 'header definition') elsif element.url.nil? && element.name.empty? SemanticNavigation.deprecation_message(:method, 'item', 'header', 'divider definition') end end @sub_elements.push element end def header(id, options={}) options[:id] = id.to_sym options[:render_if] = [options[:render_if], *@scope_render_if].compact options[:url] = nil options[:i18n_name] = @i18n_name @sub_elements.push Leaf.new(options, @level+1) end def divider(options = {}) options[:id] = :divider options[:render_if] ||= [options[:render_if], *@scope_render_if].compact options[:url] = nil options[:i18n_name] = nil options[:name] = nil @sub_elements.push Leaf.new(options, @level+1) end def method_missing(m,*args,&block) if m.to_s.match(/^[_]+$/).to_a.size > 0 divider else super(m,args,&block) end end def scope(options = {}, &block) @scope_url ||= options[:url] (@scope_render_if ||= []).push options[:render_if] self.instance_eval &block @scope_render_if.pop @scope_url = {} end private def scope_url_params(url) if url.is_a? Hash (@scope_url || {}).merge(url) else url end end def decode_url(url) if url.is_a? String controller_name, action_name = url.split('#') if controller_name && action_name decoded_url = {:controller => controller_name, :action => action_name} end end decoded_url || url end end end end end
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :point do title { Faker::Lorem.words.join(' ') } score 1 description { Faker::Lorem.paragraph } pointable nil article end end
module Admin module CmsHelper def link_to_section_edit(contents_key, link_text=nil) found_content = CachedContents.all( :conditions => { :contents_key => [ contents_key, "#{contents_key}_preview" ] }, :order => "contents_key DESC" ) cached_content = if found_content.empty? CachedContents.create!(:contents_key => contents_key, :name => contents_key) else found_content.first end final_text = link_text || cached_content.name || contents_key link_to final_text, url_for(:controller => "cms", :action => "edit", :id => cached_content.id) end end end
class AddDiscourseTopicIdToLessons < ActiveRecord::Migration def change add_column :lessons, :discourse_topic_id, :integer end end
module Strumbar module Instrumentation module ActionController def self.load(options={}) options[:rate] ||= Strumbar.default_rate using_mongoid = options.fetch(:mongoid, false) Strumbar.subscribe /process_action.action_controller/ do |client, event| key = "#{event.payload[:controller]}.#{event.payload[:action]}" db_runtime_key = using_mongoid ? :mongo_runtime : :db_runtime client.timing "#{key}.total_time", event.duration, options[:rate] client.timing "#{key}.view_time", event.payload[:view_runtime], options[:rate] client.timing "#{key}.db_time", event.payload[db_runtime_key], options[:rate] client.increment "#{key}.status.#{event.payload[:status]}", options[:rate] end end end end end
require 'spec_helper' describe Directory do context 'add_organization' do before do @organization = FactoryGirl.create(:organization, status: 'new') FactoryGirl.create(:organization_admin, organization: @organization, role: 'Primary') DirectoryApi.stub!(:create_organization) DirectoryApi.stub!(:create_contact) DirectoryApi.stub!(:create_organization_contact) @admin = double(AdminAccount) AdminAccount.stub(:new).and_return(@admin) FactoryGirl.create(:organization_admin, organization: @organization, role: 'Secondary') end it 'should create contacts for an primary, and secondary contacts' do DirectoryApi.should_receive(:create_contact).exactly(2).times Directory.add_organization(@organization) end it 'should create and organization contact for an organization' do DirectoryApi.should_receive(:create_organization_contact).exactly(1).times Directory.add_organization(@organization) end it 'calls DirectoryApi with two arguments' do DirectoryApi.should_receive(:create_organization).with(@organization, @organization.as_contact, @organization.primary_organization_administrator, @organization.secondary_organization_administrator) Directory.add_organization(@organization) end end end
class CreateTimesheets < ActiveRecord::Migration def change create_table :timesheets do |t| t.integer :sp_id, :null => false t.integer :user_id, :null => false t.datetime :start_timestamp, :null => false t.datetime :end_timestamp, :null => false t.integer :in_day, :null => false t.timestamps null: false end end end
class RemoveUsersIdentifier < ActiveRecord::Migration[6.1] def change remove_column :users, :identifier, :string, index: true end end
class CatAddQuickLink < ActiveRecord::Migration def self.up add_column :categories, :quick_link, :boolean, :default => false end def self.down remove_column :categories, :quick_link end end
class DreamSerializer include FastJsonapi::ObjectSerializer attributes :title, :description, :date, :category_id, :favorite belongs_to :category end
class Flow < ApplicationRecord belongs_to :recipe, optional: true mount_uploader :image, ImageUploader end
class ConditionColorIndicator < ConditionSimple def initialize(indicator) @indicator = indicator.downcase.gsub(/ml/, "").chars.to_set @indicator_name = Color.color_indicator_name(@indicator) end # Only exact match # For "has no color indicator" use -ind:* def match?(card) card.color_indicator and @indicator_name == card.color_indicator end def to_s "ind:#{@indicator.to_a.join}" end end
require 'rails_helper' require 'database_cleaner' RSpec.describe Api::V1::Merchants::SearchController, type: :controller do describe "GET /merchants/find" do it "returns a specific merchant" do m1 = Merchant.create(name: "amazon") m2 = Merchant.create(name: "etsy") get :show, name: "amazon", format: :json body = JSON.parse(response.body) merchant_name = body["name"] expect(response.status).to eq 200 expect(merchant_name).to eq("amazon") end end describe "GET /merchants/find_all" do it "returns a specific list of merchants" do m1 = Merchant.create(name: "amazon") m2 = Merchant.create(name: "amazon") m3 = Merchant.create(name: "etsy") get :index, name: "amazon", format: :json body = JSON.parse(response.body) merchant_names = body.map {|m| m["name"]} expect(response.status).to eq 200 expect(merchant_names).to match_array(["amazon", "amazon"]) end end end
class Admin::GroupsController < Admin::ApplicationController layout 'admin' active_scaffold do |config| config.columns.exclude :created_at config.columns[:title].set_link :edit config.columns[:rights].label = 'Rights for forum' config.list.columns = \ config.create.columns = \ config.update.columns = [:title, :rights] end end
class CreateProducts < ActiveRecord::Migration def change create_table :products do |t| t.string "title" t.boolean "new" t.integer "status" t.string "type" t.integer "brand_id" t.integer "model_id" t.integer "year" t.string "city" t.string "brake" t.integer "size_id" t.integer "speed_id" t.decimal "amount", :precision => 9, :scale => 2 t.text "description" t.float "mileage" t.float "cylinder_capacity" t.string "color" t.integer "fuel_id" t.timestamps end end end
require 'spreadsheet' namespace :import do desc 'Import provinces to database' task :provinces => :environment do p 'Import provinces...' book = open_file if book province_worksheet = 0 book.worksheet(province_worksheet).each_with_index do |row, index| next if index == 0 Province.create(code: row[0], name: "#{row[2]} #{row[1]}", province_type: row[2]) end else p 'Could not open file' end end desc 'Import districts to database' task :districts => :environment do p 'Import districts...' book = open_file if book district_worksheet = 1 book.worksheet(district_worksheet).each_with_index do |row, index| next if index == 0 province_code = row[4] province = Province.find_by(code: province_code) if province province.districts.create(code: row[0], name: "#{row[2]} #{row[1]}") else p "Can not find province with code #{province_code}" end end else p 'Could not open file' end end desc 'Import wards to database' task :wards => :environment do p 'Import wards...' book = open_file if book ward_worksheet = 2 book.worksheet(ward_worksheet).each_with_index do |row, index| next if index == 0 district_code = row[4] district = District.find_by(code: district_code) if district district.wards.create(code: row[0], name: "#{row[2]} #{row[1]}") else p "Can not find district with code #{district_code}" end end else p 'Could not open file' end end desc 'Import provinces, districts and wards to database' task :all => [:provinces, :districts, :wards] end # set default rake task with the same file name task :import => 'import:all' def open_file path = ENV['path'] || File.join(Rails.root, 'db', 'data.xls') Spreadsheet.open(path) rescue false end
class CommentToCommentary < ApplicationRecord belongs_to :user belongs_to :commentary end
module ClientPkgServe def broker_urls ::RSence.config[:broker_urls] end def match( uri, request_type ) uri.match( /^#{broker_urls[:h]}/ ) end # Helper method to return the time formatted according to the HTTP RFC def httime(time) return time.gmtime.strftime('%a, %d %b %Y %H:%M:%S %Z') end def build_busy_wait while @build_busy puts "-- build not finished, waiting.. --" sleep 0.4 end end def set_headers( response ) # Sets the response date header to the current time: response['Date'] = httime( Time.now ) # Controls caching with headers based on the configuration if ::RSence.config[:cache_maximize] response['Expires'] = httime(Time.now+::RSence.config[:cache_expire]) else response['Cache-Control'] = 'no-cache' end end def check_ua( request ) support_gzip = (request.header.has_key?('Accept-Encoding') and request.header['Accept-Encoding'].include?('gzip')) support_gzip = false if ::RSence.config[:no_gzip] if request.header.has_key?('User-Agent') ua = request.header['User-Agent'] is_safari = ua.include?("WebKit") is_msie = (not ua.include?("Opera")) and ua.include?("MSIE") end if is_safari version = ua.split( 'WebKit/' )[1].split('.')[0].to_i else version = 0 # not used for others end return { :safari => is_safari, :msie => is_msie, :version => version } end def support_gzip?( ua ) doesnt_support = (ua[:safari] and ua[:version] < 533) return ( not doesnt_support ) end def serve_js( request, response, request_path, ua ) # the file-specific identifier ('core', 'basic' etc) req_file = request_path[3][0..-4] if not @client_cache.js_cache.has_key?( req_file ) response.status = 404 response.body = '/* 404 - Not Found */' else response.status = 200 response['Content-Type'] = 'text/javascript; charset=utf-8' # these browsers have issues with gzipped js content support_gzip = support_gzip?( ua ) if support_gzip #response['Transfer-Encoding'] = 'chunked,gzip' response['Last-Modified'] = @client_cache.last_modified body = @client_cache.gz_cache[ req_file ]+"\r\n\r\n" response['Content-Length'] = body.bytesize.to_s response['Content-Encoding'] = 'gzip' response.body = body else response['Last-Modified'] = @client_cache.last_modified body = @client_cache.js_cache[ req_file ] response['Content-Length'] = body.bytesize.to_s response.body = body end end end def serve_theme( request, response, request_path, ua ) # Get the name of the theme theme_name = request_path[3] # Get the theme resource type (html/css/gfx) theme_part = request_path[4].to_sym # Get the theme resource identifier req_file = request_path[5] # checks for theme name has_theme = @client_cache.theme_cache.has_key?( theme_name ) # checks for theme part (css/html/gfx) if theme_part == :css or theme_part == :html has_theme_part = false else has_theme_part = ( has_theme and @client_cache.theme_cache[theme_name].has_key?(theme_part) ) end # checks for theme file has_theme_file = ( has_theme_part and @client_cache.theme_cache[theme_name][theme_part].has_key?( req_file ) ) if not has_theme response.status = 404 response.body = '404 - Theme Not Found' puts "Theme #{theme_name} not found, avail: #{@client_cache.theme_cache.keys.join(', ')}" if RSence.args[:verbose] elsif not has_theme_part response.status = 503 response.body = '503 - Invalid Theme Part Request' elsif not has_theme_file response.status = 404 response.body = '404 - Theme Resource Not Found' puts "File not found, avail: #{@client_cache.theme_cache[theme_name][theme_part].keys.join(', ')}" if RSence.args[:verbose] else response.status = 200 file_ext = req_file.split('.')[-1] response['Content-Type'] = { 'png' => 'image/png', 'jpg' => 'image/jpeg', 'gif' => 'image/gif', 'swf' => 'application/x-shockwave-flash' }[file_ext] response['Last-Modified'] = @client_cache.last_modified body = @client_cache.theme_cache[theme_name][theme_part][req_file] if body.nil? warn "ClientPkgServe#get: empty body for #{request.path}" body = '' end response['Content-Length'] = body.bytesize.to_s response.body = body end end ## Responds to get-requests def get( request, response, session ) if @build_busy puts "#{Time.now.strftime('%Y-%m-%d %H:%M:%S')} -- Client build busy." response['Retry-After'] = '1' response['Content-Type'] = 'text/plain' response['Refresh'] = "1; #{env['REQUEST_URI']}" response['Content-Length'] = '0' response.body = '' response.status = 503 end ua = check_ua( request ) set_headers( response ) ## Split path into an array for determining what to serve request_uri = '/'+request.path.match( /^#{::RSence.config[:broker_urls][:h]}(.*)$/ )[1] request_path = request_uri.split( '/' ) ## Requested type of client resource (js/themes) req_type = request_path[2] unless ['js','themes'].include? req_type req_rev = req_type req_type = request_path[3] request_path.delete_at(2) end ## Serve compiled client javascript component files: if req_type == 'js' serve_js( request, response, request_path, ua ) ## Serve client theme files elsif req_type == 'themes' serve_theme( request, response, request_path, ua ) end end end
class BooksController < ApplicationController get "/books/new" do erb :'/index' end post "/api/books" do authenticate book = Book.find_by(isbn_13: json_request_body[:isbn_13]) if book json(book.as_json) else new_book = Book.new( authors: json_request_body[:authors], cover_url: json_request_body[:cover_url], isbn_13: json_request_body[:isbn_13], pages: json_request_body[:page_count].to_i, preview_url: json_request_body[:preview_url], rating: json_request_body[:rating], title: json_request_body[:title] ) if new_book.save json(new_book.as_json) else status(422) new_book_json = new_book.as_json new_book_json[:errors] = new_book.errors.full_messages json(new_book_json) end end end end
class Yard2steep::AST::ConstantNode @name: any @klass: any @v_type: any def name: -> any def klass: -> any def v_type: -> any def initialize: (name: String, klass: String, v_type: String) -> any def long_name: -> String end
require 'spec_helper' describe AdditionalCostsDeploymentsController do render_views let(:user) { User.make! } before(:each) do sign_in user @deployment = given_resources_for([:deployment], :user => user)[:deployment] @additional_cost = AdditionalCost.make!(:user => user) end it "should render index" do get :index, :deployment_id => @deployment.id response.code.should == "200" assigns(:deployment).should == @deployment response.should render_template("index") end context "update" do it "should add the additional cost to deployment" do put :update, :deployment_id => @deployment.id, :id => @additional_cost.id response.code.should == "200" @deployment.additional_costs =~ @additional_cost assigns(:deployment).should == @deployment end it "should remote the additional cost from deployment" do # Make two update requests, the first adds as per the previous test, the second should remove it again put :update, :deployment_id => @deployment.id, :id => @additional_cost.id put :update, :deployment_id => @deployment.id, :id => @additional_cost.id response.code.should == "200" @deployment.additional_costs.should_not include @additional_cost assigns(:deployment).should == @deployment end end end
# Copyright (C) 2011-2014 Tanaka Akira <akr@fsij.org> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # 3. The name of the author may not be used to endorse or promote # products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE # GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE # OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, # EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. class Tb::Cmd @subcommands = [] @default_option = { :opt_help => 0, :opt_N => nil, :opt_debug => 0, :opt_no_pager => nil, :opt_output => nil, } def self.reset_option @default_option.each {|k, v| instance_variable_set("@#{k}", Marshal.load(Marshal.dump(v))) } end def self.init_option class << Tb::Cmd Tb::Cmd.default_option.each {|k, v| attr_accessor k } end reset_option end def self.define_common_option(op, short_opts, *long_opts) if short_opts.include? "h" op.def_option('-h', '--help', 'show help message (-hh for verbose help)') { Tb::Cmd.opt_help += 1 } end if short_opts.include? "N" op.def_option('-N', 'use numeric field name') { Tb::Cmd.opt_N = true } end if short_opts.include? "o" op.def_option('-o filename', 'output to specified filename') {|filename| Tb::Cmd.opt_output = filename } end if long_opts.include? "--no-pager" op.def_option('--no-pager', 'don\'t use pager') { Tb::Cmd.opt_no_pager = true } end opts = [] opts << '-d' if short_opts.include?('d') opts << '--debug' if long_opts.include?('--debug') if !opts.empty? op.def_option(*(opts + ['show debug message'])) { Tb::Cmd.opt_debug += 1 } end end @verbose_help = {} def self.def_vhelp(subcommand, str) if @verbose_help[subcommand] raise ArgumentError, "verbose_help[#{subcommand.dump}] already defined." end @verbose_help[subcommand] = str end def self.subcommand_send(prefix, subcommand, *args, &block) self.send(prefix + "_" + subcommand.gsub(/-/, '_'), *args, &block) end end class << Tb::Cmd attr_reader :subcommands attr_reader :default_option attr_reader :verbose_help end def err(msg) raise SystemExit.new(1, msg) end def parse_aggregator_spec(spec) case spec when 'count' ['count', nil] when /\Asum\((.*)\)\z/ ['sum', $1] when /\Aavg\((.*)\)\z/ ['avg', $1] when /\Amax\((.*)\)\z/ ['max', $1] when /\Amin\((.*)\)\z/ ['min', $1] when /\Avalues\((.*)\)\z/ ['values', $1] when /\Auniquevalues\((.*)\)\z/ ['uniquevalues', $1] else raise ArgumentError, "unexpected aggregation spec: #{spec.inspect}" end end def parse_aggregator_spec2(spec) name, field = parse_aggregator_spec(spec) func = Tb::Func::AggregationFunctions[name] if !func raise ArgumentError, "unexpected aggregation spec: #{spec.inspect}" end [func, field] end def split_field_list_argument(arg) split_csv_argument(arg).map {|f| f || '' } end def split_csv_argument(arg) return CSV.new(arg).shift || [] end def tablereader_open(filename, &b) Tb.open_reader(filename, Tb::Cmd.opt_N, &b) end def with_output(filename=Tb::Cmd.opt_output) if filename && filename != '-' tmp = filename + ".part" begin File.open(tmp, 'w') {|f| yield f } if File.exist?(filename) && FileUtils.compare_file(filename, tmp) File.unlink tmp else File.rename tmp, filename end ensure File.unlink tmp if File.exist? tmp end elsif $stdout.tty? && !Tb::Cmd.opt_no_pager Tb::Pager.open {|pager| yield pager } else yield $stdout end end def output_tbenum(te) filename = Tb::Cmd.opt_output || '-' numeric = Tb::Cmd.opt_N filename, fmt = Tb.undecorate_filename(filename, numeric) factory = Tb::FormatHash.fetch(fmt)[:writer] with_output(filename) {|out| writer = factory.new(out) te.write_with(writer) } end
require 'bcrypt' class Maker include DataMapper::Resource attr_reader :password attr_accessor :password_confirmation validates_confirmation_of :password property :id, Serial property :full_name, String, required: true property :user_name, String, required: true property :email, String, format: :email_address, required: true property :password_digest, Text has n, :peeps def password=(password) @password = password self.password_digest = BCrypt::Password.create(password) end def self.authenticate(email, password) maker = first(email: email) if maker && BCrypt::Password.new(maker.password_digest) == password maker end end def user_exists?(maker) maker.exists? ? maker : false end def password_check(email, password) maker = first(email: email) BCrypt::Password.new(maker.password_digest) == password end end
# encoding: utf-8 control "V-92653" do title "The Apache web server must have resource mappings set to disable the serving of certain file types." desc "Resource mapping is the process of tying a particular file type to a process in the web server that can serve that type of file to a requesting client and to identify which file types are not to be delivered to a client. By not specifying which files can and cannot be served to a user, the web server could deliver to a user web server configuration files, log files, password files, etc. The web server must only allow hosted application file types to be served to a user, and all other types must be disabled. " impact 0.5 tag "check": "Determine the location of the 'HTTPD_ROOT' directory and the 'httpd.conf' file: # httpd -V | egrep -i 'httpd_root|server_config_file' -D HTTPD_ROOT='/etc/httpd' -D SERVER_CONFIG_FILE='conf/httpd.conf' Review any 'Action' or 'AddHandler' directives: # cat /<path_to_file>/httpd.conf | grep -i 'Action' # cat /<path_to_file>/httpd.conf | grep -i 'AddHandler' If 'Action' or 'AddHandler' exist and they configure .exe, .dll, .com, .bat, or .csh, or any other shell as a viewer for documents, this is a finding. If this is not documented and approved by the Information System Security Officer (ISSO), this is a finding." tag "fix": "Determine the location of the 'HTTPD_ROOT' directory and the 'httpd.conf' file: # httpd -V | egrep -i 'httpd_root|server_config_file' -D HTTPD_ROOT='/etc/httpd' -D SERVER_CONFIG_FILE='conf/httpd.conf' Disable MIME types for .exe, .dll, .com, .bat, and .csh programs. If 'Action' or 'AddHandler' exist within the 'httpd.conf' file and they configure .exe, .dll, .com, .bat, or .csh, remove those references. Restart Apache: apachectl restart Ensure this process is documented and approved by the ISSO." # Write Check Logic Here describe apache_conf() do its('AddHandler') { should_not include '.exe', '.dll', '.com', '.bat', '.csh', '.sh', '.zsh' } end describe apache_conf() do its('Action') { should_not include '.exe', '.dll', '.com', '.bat', '.csh', '.sh', '.zsh' } end end
# frozen_string_literal: true FactoryBot.define do factory :screening do movie cinema_hall screening_time { DateTime.current } end end
class OrdersController < ApplicationController skip_before_action :require_login before_action :find_cart, only: [ :clear_cart, :submit_order, :checkout ] before_action :find_order, only: [ :show_complete, :cancel] def cart if session[:cart_id] @order = Order.find_by(id: session[:cart_id]) else @order = Order.new if @order.save session[:cart_id] = @order.id end end end def clear_cart @order.clear_cart flash[:success] = "Cart cleared." redirect_to cart_path end def checkout; end def submit_order @order.submit_order if filter_cc && @order.update(order_params) session[:cart_id] = nil flash[:success] = "Your order has been submitted!" redirect_to complete_order_path(@order) return else flash.now[:error] = "A problem occurred: Could not submit order" render :checkout return end end def show_complete; end def cancel if @order.cancel flash[:success] = "This order has been cancelled." else flash[:error] = "The following items could not be cancelled: #{@order.errors.messages.values}" end redirect_to complete_order_path(@order) return end private def find_cart @order = Order.find_by(id: session[:cart_id]) if @order.nil? head :not_found return end end def find_order @order = Order.find_by(id: params[:id]) if @order.nil? head :not_found return end end def filter_cc if @order.cc_num_is_correct(params[:order][:cc_last_four]) params[:order][:cc_last_four] = params[:order][:cc_last_four][-4..-1] return true else return false end end def order_params return params.require(:order).permit(:name, :email, :address, :cc_last_four, :cc_exp_year, :cc_exp_month, :cc_cvv) end end
class HomeController < ApplicationController def get_infomercial_ipsum if params[:number_of_paragraphs].present? number_of_paragraphs = params[:number_of_paragraphs].to_i informercial_ipsum_request = InfomercialIpsumRequest.new(number_of_paragraphs) @informercial_ipsum = informercial_ipsum_request.content end end end
RSpec.describe "Users can create a external income" do context "when signed in as a partner organisation user" do let(:financial_quarter) { FinancialQuarter.new(Time.current.year, 1) } let(:user) { create(:partner_organisation_user) } let(:programme) { create(:programme_activity, extending_organisation: user.organisation) } let!(:project) { create(:project_activity, :with_report, organisation: user.organisation, parent: programme) } let!(:external_income_provider) { create(:external_income_provider) } before { authenticate!(user: user) } after { logout } before do visit organisation_activity_path(project.organisation, project) click_on "Other funding" click_on t("page_content.external_income.button.create") end scenario "they can add an external income" do template = build(:external_income, organisation: external_income_provider, amount: "2345", financial_quarter: financial_quarter.quarter, financial_year: financial_quarter.financial_year.start_year, oda_funding: true) fill_in_external_income_form(template) expect(page).to have_content(t("action.external_income.create.success")) external_income = ExternalIncome.order("created_at ASC").last expect(external_income.organisation).to eq(external_income_provider) expect(external_income.financial_quarter).to eq(financial_quarter.quarter) expect(external_income.financial_year).to eq(financial_quarter.financial_year.start_year) expect(external_income.amount).to eq(2345.00) expect(external_income.oda_funding).to be(true) within("table.implementing_organisations") do expect(page).to have_content(external_income_provider.name) expect(page).to have_content(financial_quarter.to_s) expect(page).to have_content("£2,345.00") expect(page).to have_content("Yes") end end context "when the current fin. year has advanced from the period being reported" do scenario "can choose the previous financial year" do options = page.all("#external-income-financial-year-field option").map(&:text) expect(options).to include(FinancialYear.new(Date.today.year).pred.to_s) end end scenario "they are shown errors when required fields are left blank" do click_on t("default.button.submit") expect(page).to have_content("Organisation can't be blank") expect(page).to have_content("Financial quarter can't be blank") expect(page).to have_content("Amount can't be blank") end end end
#!/usr/bin/env ruby # # Reads in multiple JSON documents and generates a # master JSON schema to define them all. # # Input is a directory continaing one or more JSON # JSON docs (*.json). Each *.json file must # contain one valid JSON document. # dir = File.dirname(__FILE__) $: << File.expand_path("#{dir}/lib") require "json" require 'yaml' require 'recursive_open_struct' # https://github.com/aetherknight/recursive-open-struct.git require "json-schema-generator" # https://github.com/maxlinc/json-schema-generator require "hashdiff" # https://github.com/liufengyun/hashdiff require "json-schema" # https://github.com/hoxworth/json-schema require "schema" require "util" config = YAML.load_file("config.yml") $debug = config['debug'] directory = ARGV.first abort "no source directory provided\n#{Util.usage}" if !directory docs = Util.read_json_files(directory) master_schema = Schema.new Util.log "building master schema" docs.each_with_index do |doc, index| master_schema.extractor(JSON.parse(doc[:text])) doc_schema = JSON::SchemaGenerator.generate 'schemer', doc[:text], {:schema_version => 'draft3'} differences = HashDiff.diff(JSON.parse(master_schema.to_json), JSON.parse(doc_schema)) differences.each do |action, key, value, new_value| case action when '+' master_schema.insert(key, value) Util.debug "#{doc[:filename]}: added new mandatory field '#{key}' to master with value #{value}" if index != 0 if master_schema.has_key? "#{key}.required" master_schema.insert("#{key}.required", false) Util.debug "#{doc[:filename]}: changed field '#{key}' to optional" end end when '-' if master_schema.has_key? "#{key}.required" master_schema.insert("#{key}.required", false) Util.debug "#{doc[:filename]}: set field '#{key}' to optional" end when '~' Util.debug "#{doc[:filename]}: no change required for '#{key}'" else abort "#{doc[:filename]}: action #{action} not understood" end end end config['fields_that_can_be_null'].each do |f| cfg = master_schema.retrieve "properties.#{f}.type" master_schema.insert("properties.#{f}.type", JSON.parse("[ \"null\", \"#{cfg}\" ]")) if cfg end Util.log "validating all docs against master schema" docs.each do |doc| begin passed = JSON::Validator.validate!(master_schema.to_json, JSON.parse(doc[:text], { :version => 'draft3' })) abort "#{doc} failed schema test" if !passed rescue JSON::Schema::ValidationError => e doc_json = JSON.pretty_generate(JSON.parse(doc[:text])) sch_json = JSON.pretty_generate(JSON.parse(master_schema.to_json)) abort "#{e}\n\n#{doc_json}\n\n#{sch_json}" end end master_schema.summary_report("#{config['www_root']}/doc.json")
require "octokit" require "fileutils" require "base64" require "bundler" require "json" abort("Please set ENV[\"GITHUB_USERNAME\"] and/or ENV[\"GITHUB_PASSWORD\"] and try again") unless ENV["GITHUB_USERNAME"] && ENV["GITHUB_USERNAME"] abort("Oops, looks like you forgot to specify a Github organization name. Please try again.") unless ARGV.size >= 1 Octokit.configure do |c| c.login = ENV["GITHUB_USERNAME"] c.password = ENV["GITHUB_PASSWORD"] end TMP_DIR = ".bundle" FileUtils.mkdir TMP_DIR r = Octokit.search_code("Gemfile.lock in:path user:#{ARGV[0]} NOT migrations", :per_page => 100) repositories = [] specs = {} r.items.each do |i| f = Octokit.content(i.repository.full_name, path: i.path) d = Base64.decode64(f.content) gemfile = Bundler::LockfileParser.new(d) tmp_hash = { :name => "#{i.repository.name}", :sources => gemfile.sources, :specs => gemfile.specs, :dependencies => gemfile.dependencies, :platforms => gemfile.platforms, :bundler_version => gemfile.bundler_version } repositories << tmp_hash tmp_hash[:specs].each do |d| gemname = d.to_s.split(" ").first version = d.to_s.split(/[()]/).last specs[gemname] ||= { :versions => [], :usage => [] } specs[gemname][:versions] << version unless specs[gemname][:versions].include? version specs[gemname][:usage] << tmp_hash[:name] end puts "Parsing " + i.repository.name + "...\nDONE." end repositories.sort_by! { |h| h[:name] } File.open("data.json", "w") do |f| puts "Writing data.json..." data_hash = { "repositories" => repositories, "gems" => specs.map { |k,v| { name: k, versions: v[:versions].sort, usage: v[:usage].sort }} } f.write(data_hash.to_json) end puts "Cleaning up..." FileUtils.rm_rf(TMP_DIR) if File.exists?(TMP_DIR) puts "Finished."
require File.dirname(__FILE__) + '/spec_helper' module MethodMatching describe ExtendableBlock do it "should give a friendly message when block is called but none is set" do ExtendableBlock.new { block.call }. should raise_error(/No block given/) end end end
class ResultsController < ApplicationController def show @result = Result.find(params[:id]) end def new @result = Result.new @quizzes = Quiz.all end def create @result = Result.new(result_params) if @result.save flash[:success] = "Your result has been created!" redirect_to @result else flash[:notice] = "There was a problem and your result wasn't saved. Please try again." render 'new' end end private def result_params params.require(:result).permit(:title, :description, :quiz_id) end end
# Copyright © 2011-2019 MUSC Foundation for Research Development~ # All rights reserved.~ # Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:~ # 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.~ # 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following~ # disclaimer in the documentation and/or other materials provided with the distribution.~ # 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products~ # derived from this software without specific prior written permission.~ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,~ # BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT~ # SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL~ # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS~ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR~ # TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.~ require 'rails_helper' RSpec.describe 'dashboard/sub_service_requests/_request_details', type: :view do include RSpecHtmlMatchers context "Export to excel" do it "should display service_request_id and sub_service_request_id in href" do protocol = create(:protocol, :without_validations, selected_for_epic: true) service_request = create(:service_request, :without_validations, protocol: protocol) org = create(:organization) create(:service, organization: org, send_to_epic: true) sub_service_request = create(:sub_service_request, protocol: protocol, service_request: service_request, organization: org) render_request_details(protocol: protocol, service_request: service_request, sub_service_request: sub_service_request) expect(response).to have_tag('a', with: { href: service_request_path(srid: service_request.id, admin_offset: 1, report_type: 'request_report', sub_service_request_id: sub_service_request.id, format: :xlsx) }, text: "Export to Excel") end end context "use_epic truthy" do stub_config("use_epic", true) it "should display 'Send to Epic' button" do protocol = create(:protocol, :without_validations, selected_for_epic: true) service_request = create(:service_request, :without_validations, protocol: protocol) org = create(:organization) create(:service, organization: org, send_to_epic: true) sub_service_request = create(:sub_service_request, protocol: protocol, service_request: service_request, organization: org) render_request_details(protocol: protocol, service_request: service_request, sub_service_request: sub_service_request) expect(response).to have_tag("button", text: /Send to Epic/) end end context "use_epic falsey" do stub_config("use_epic", false) it "should not display 'Send to Epic' button" do protocol = create(:protocol, :without_validations, selected_for_epic: true) service_request = create(:service_request, :without_validations, protocol: protocol) org = create(:organization) create(:service, organization: org, send_to_epic: true) sub_service_request = create(:sub_service_request, protocol: protocol, service_request: service_request, organization: org) render_request_details(protocol: protocol, service_request: service_request, sub_service_request: sub_service_request) expect(response).not_to have_tag("button", text: /Send to Epic/) end end context "SubServiceRequest associated with CTRC Organization" do it "should display 'Administrative Approvals' button" do protocol = create(:protocol, :without_validations, selected_for_epic: true) service_request = create(:service_request, :without_validations, protocol: protocol) org = create(:organization, :ctrc) create(:service, organization: org, send_to_epic: true) sub_service_request = create(:sub_service_request, protocol: protocol, service_request: service_request, organization: org) render_request_details(protocol: protocol, service_request: service_request, sub_service_request: sub_service_request) expect(response).to have_tag("button", text: /Administrative Approvals/) end end context "SubServiceRequest eligible for Subsidy" do it "should render subsidies" do protocol = stub_protocol service_request = stub_service_request(protocol: protocol) sub_service_request = stub_sub_service_request(service_request: service_request, protocol: protocol, eligible_for_subsidy?: true) allow(sub_service_request).to receive_messages(approved_subsidy: nil, pending_subsidy: nil) render_request_details(protocol: protocol, service_request: service_request, sub_service_request: sub_service_request) expect(response).to render_template(partial: "dashboard/subsidies/_subsidy", locals: { sub_service_request: sub_service_request, admin: true }) end end context "SubServiceRequest not eligible for Subsidy" do it "should not render subsidies" do protocol = stub_protocol service_request = stub_service_request(protocol: protocol) stub_sub_service_request(service_request: service_request, eligible_for_subsidy?: false) expect(response).not_to render_template(partial: "dashboard/subsidies/_subsidy") end end def render_request_details(opts = {}) render "dashboard/sub_service_requests/request_details", opts end def stub_protocol build_stubbed(:protocol) end def stub_service_request(opts = {}) build_stubbed(:service_request, protocol: opts[:protocol]) end # specify protocol and organization def stub_sub_service_request(opts = {}) obj = build_stubbed(:sub_service_request, service_request: opts[:service_request], protocol: opts[:protocol]) allow(obj).to receive(:ctrc?). and_return(!!opts[:ctrc?]) allow(obj).to receive(:eligible_for_subsidy?). and_return(!!opts[:eligible_for_subsidy?]) obj end def stub_organization(opts = {}) build_stubbed(:organization) end def stub_current_user(user) ActionView::Base.send(:define_method, :current_user) { user } end end
module SCSSLint # Checks for nesting depths class Linter::NestingDepth < Linter include LinterRegistry def visit_root(_node) @max_depth = config['max_depth'] @depth = 0 yield # Continue linting children end def visit_rule(node) if !node.node_parent.respond_to?(:parsed_rules) # first level rules should reset depth to 0 @depth = 0 elsif node.node_parent == @last_parent # reset to last depth if node is a sibling @depth = @last_depth else @depth += 1 end if @depth > @max_depth add_lint(node.parsed_rules, 'Nesting should be no greater than ' \ "#{@max_depth}, but was #{@depth}") else yield # Continue linting children @last_parent = node.node_parent @last_depth = @depth end end end end
class EventTimeValidator < ActiveModel::Validator def validate(record) if record.start_time < Time.now record.errors[:start_time] << "cannot be in the past" end if record.end_time < record.start_time record.errors[:end_time] << "must be after start time" end end end
# # Cookbook Name:: weechat-cookbook # Recipe:: default # require_recipe "weechat::scripts" package 'weechat' do package_name = value_for_platform( ['debian', 'ubuntu'] => {'default' => 'weechat-curses'}, ['mac_os_x'] => {'default' => 'weechat'} ) action :install end node[:weechat][:users].each do |user| user_home = UserUtilities.home_directory_for_user(user[:name]) weechat_home = File.join(user_home, ".weechat") directory weechat_home do owner user[:name] mode "0700" action :create end template File.join(weechat_home, "alias.conf") do source "alias.conf.erb" end if user[:irc] && user[:irc][:servers] template File.join(weechat_home, "irc.conf") do source "irc.conf.erb" variables( :servers => user[:irc][:servers] || [] ) end end if user[:jabber] template File.join(weechat_home, "jabber.conf") do source "jabber.conf.erb" variables( :servers => user[:jabber][:servers] || [] ) end end template File.join(weechat_home, "weechat.conf") do source "weechat.conf.erb" end template File.join(weechat_home, "logger.conf") do source "logger.conf.erb" end execute "update weechat owner to #{user[:name]}" do command "chown -R #{user[:name]} #{weechat_home}" end execute "update weechat mode" do command "chmod -R 700 #{weechat_home}" end end
# frozen_string_literal: true module SharedFunctions def uploaded_file(file = Rails.root.join('spec', 'support', 'images', 'test.png')) Rack::Test::UploadedFile.new(file) end end RSpec.configure do |config| config.include SharedFunctions end
class Admin::DepartmentsController < AdminController def index @departments = Department.order(:title) end def show @department = Department.find_by_id(params[:id]) end def new @department = Department.new end def create @department = Department.new(params[:department]) if @department.save flash[:notice] = "You have created a new department!" redirect_to admin_departments_path else flash[:notice] = "Department not saved" render :action => 'new' end end def edit @department = Department.find(params[:id]) end def update @department = Department.find(params[:id]) if @department.update_attributes(params[:department]) flash[:notice] = "Department was successfully updated." redirect_to admin_departments_path else flash[:notice] = "Update was not saved." render :action => 'edit' end end def destroy @department = Department.find(params[:id]) @department.destroy redirect_to admin_departments_path end end
class WorkspacesController < ApplicationController wrap_parameters :exclude => [] def index if params[:user_id] user = User.find(params[:user_id]) workspaces = user.workspaces.workspaces_for(current_user) else workspaces = Workspace.workspaces_for(current_user) end workspaces = workspaces.active if params[:active] present paginate(workspaces.includes([:owner, :archiver, {:sandbox => {:database => :gpdb_instance}}]).order("lower(name) ASC")), :presenter_options => {:show_latest_comments => params[:show_latest_comments] == 'true'} end def create workspace = current_user.owned_workspaces.build(params[:workspace]) Workspace.transaction do workspace.save! workspace.public ? Events::PublicWorkspaceCreated.by(current_user).add(:workspace => workspace) : Events::PrivateWorkspaceCreated.by(current_user).add(:workspace => workspace) end present workspace, :status => :created end def show workspace = Workspace.find(params[:id]) authorize! :show, workspace present workspace, :presenter_options => {:show_latest_comments => params[:show_latest_comments] == 'true'} end def update workspace = Workspace.find(params[:id]) original_archived = workspace.archived?.to_s attributes = params[:workspace] attributes[:archiver] = current_user if attributes[:archived] == 'true' workspace.attributes = attributes authorize! :update, workspace Workspace.transaction do if attributes[:schema_name] create_schema = true begin if attributes[:database_name] gpdb_instance = GpdbInstance.find(attributes[:instance_id]) database = gpdb_instance.create_database(attributes[:database_name], current_user) create_schema = false if attributes[:schema_name] == "public" else database = GpdbDatabase.find(attributes[:database_id]) end GpdbSchema.refresh(database.gpdb_instance.account_for_user!(current_user), database) if create_schema workspace.sandbox = database.create_schema(attributes[:schema_name], current_user) else workspace.sandbox = database.schemas.find_by_name(attributes[:schema_name]) end rescue Exception => e raise ApiValidationError.new(database ? :schema : :database, :generic, {:message => e.message}) end end create_workspace_events(workspace, original_archived) workspace.save! end present workspace end private def create_workspace_events(workspace, original_archived) if workspace.public_changed? workspace.public ? Events::WorkspaceMakePublic.by(current_user).add(:workspace => workspace) : Events::WorkspaceMakePrivate.by(current_user).add(:workspace => workspace) end if params[:workspace][:archived].present? && params[:workspace][:archived] != original_archived workspace.archived? ? Events::WorkspaceArchived.by(current_user).add(:workspace => workspace) : Events::WorkspaceUnarchived.by(current_user).add(:workspace => workspace) end if workspace.sandbox_id_changed? && workspace.sandbox Events::WorkspaceAddSandbox.by(current_user).add( :sandbox_schema => workspace.sandbox, :workspace => workspace ) end end end
module Report require 'WIN32OLE' require "Date" class ReportorError < StandardError;end class NotValidParameterError < ReportorError;end Summary_file_name = "summary\.xlsx" Directory_name = "directory" Cover_name = "cover" class Directory Result_attr = "a" Testcase_attr = "b" Detail_attr = "c" First_attr = Result_attr Last_attr = Detail_attr First_item = 2 def mark_pass row @directory.Range("#{Result_attr}#{row}:#{Detail_attr}#{row}").Interior.ColorIndex = 0 end def highlight row @directory.Range("#{First_attr}#{row}:#{Last_attr}#{row}").Interior.ColorIndex = 4 end def mark_failed row @directory.Range("#{First_attr}#{row}:#{Last_attr}#{row}").Interior.ColorIndex = 3 end def get_result row @directory.Range("#{Result_attr}#{row}").Value end def set_result row, str @directory.Range("#{Result_attr}#{row}").Value = str unless "Pass"== str mark_failed row else mark_pass row @failed_case.delete row end end def get_testcase row cell = @directory.Range("#{Testcase_attr}#{row}") # puts "Address: #{cell.Hyperlinks(1).Address}" {:text=>cell.Value, :hyperlnk=>cell.Hyperlinks(1).Address} end def set_testcase row, str, hyperlnk = nil cellpath = "#{Testcase_attr}#{row}" hyperlnk = @directory.Range(cellpath).Value unless hyperlnk @hyperlinks.Add(@directory.Range(cellpath), hyperlnk) #absolute hyperlink @directory.Range(cellpath).Value = str end def get_detailreport row @directory.Range("#{Detail_attr}#{row}").Value end def set_detailreport row, str, hyperlnk = nil cellpath = "#{Detail_attr}#{row}" hyperlnk = @directory.Range(cellpath).Value unless hyperlnk @hyperlinks.Add(@directory.Range(cellpath), hyperlnk) #relative hyperlink @directory.Range(cellpath).Value = str end def initialize sheet @directory = sheet @directory.Columns(Result_attr).ColumnWidth = 10 @directory.Columns(Testcase_attr).ColumnWidth = 120 @directory.Columns(Detail_attr).ColumnWidth = 80 @dir_row = First_item @total_case = 0 @failed_case = [] @hyperlinks = @directory.Hyperlinks end attr_reader :total_case def failed_case @failed_case.dup end def change result, row rks = result.keys set_result(row, result[:result]) if rks.include?(:result) set_testcase(row, result[:testcase][:name], result[:testcase][:where]) if rks.include?(:testcase) set_detailreport(row, result[:detail][:name], result[:detail][:where]) if rks.include?(:detail) save() end def append result @failed_case << @dir_row change result, @dir_row @dir_row += 1 @total_case += 1 end def save @directory.Parent.Save end def reconstruct ur = @directory.UsedRange row_cnt = ur.Row + ur.Rows.Count # puts "row_cnt: %d"%row_cnt (@dir_row...row_cnt).each do |row| @total_case += 1 if "Pass" != get_result(row) @failed_case << row end end @dir_row += @total_case end def exit end end class Cover COVERITEM = ["Start time:", "Total cases:", "Failed cases:", "End time:"] Attr_col = "c" Value_col = "d" def initialize sheet, items=[] @cover = sheet ur = @cover.UsedRange if (2 == ur.Row+ur.Rows.Count) #blank sheet start_row = 8 init_items start_row, items end end def reconstruct ur = @cover.UsedRange @cover_tail = ur.Row + ur.Rows.Count init_items @cover_tail end def exit total_case, failed_case @cover.Range("#{Attr_col}#{@cover_tail-2}").Value = COVERITEM[1] @cover.Range("#{Attr_col}#{@cover_tail-1}").Value = COVERITEM[2] @cover.Range("#{Attr_col}#{@cover_tail}").Value = COVERITEM[3] @cover.Range("#{Value_col}#{@cover_tail-2}").Value = total_case @cover.Range("#{Value_col}#{@cover_tail-1}").Value = failed_case @cover.Range("#{Value_col}#{@cover_tail}").Value = DateTime.now.asctime end private def init_items start_row, items=[] @cover_tail = start_row + COVERITEM.size + items.size - 1 acol = "#{Attr_col}#{start_row}:#{Attr_col}#{@cover_tail}" @cover.Range(acol).Borders.Weight = 3 @cover.Range(acol).Borders.ColorIndex = 14 @cover.Range(acol).Borders.Linestyle = 9 # sheet.Range(acol).Interior.ColorIndex = 23 @cover.Range(acol).Font.Bold = true# @cover.Columns(Attr_col).ColumnWidth = 40 vcol = "#{Value_col}#{start_row}:#{Value_col}#{@cover_tail}" @cover.Range(vcol).Borders.Weight = 1 @cover.Range(vcol).Borders.ColorIndex = 14 @cover.Range(vcol).Borders.Linestyle = 12 # sheet.Range(vcol).Interior.ColorIndex = 25 @cover.Columns(Value_col).ColumnWidth = 40 rge = "#{Attr_col}#{start_row}:#{Value_col}#{@cover_tail}" @cover.Range(rge).HorizontalAlignment = -4108 #middle @cover.Range("#{Attr_col}#{start_row}").Value = COVERITEM[0] @cover.Range("#{Value_col}#{start_row}").Value = DateTime.now.asctime i = 1 items.each do |it| break unless (it.instance_of?(Array) && (2 == it.size)) r = start_row+i @cover.Range("#{Attr_col}#{r}").Value = it[0] @cover.Range("#{Value_col}#{r}").Value = it[1] i += 1 end end end class Summary def self.instance_of? summary rst = false re = Regexp.new "%s$"%[Summary_file_name.gsub("\.", "\\.")] if summary =~ re rst = true end rst end def initialize dir, items=[] sum_ins = self.class.instance_of? dir if sum_ins @dir = File.dirname dir else @dir = dir end @excel = WIN32OLE.new("excel.application") @excel.Visible = true if sum_ins init_exist() else init_nonexist(items) end end attr_reader :directory, :cover def exit @cover.exit @directory.total_case, @directory.failed_case.size @directory.exit @book.Save @book.Saved = true @book.Close @excel.Quit end private def init_nonexist items @book = @excel.Workbooks.Add cov = @book.Worksheets(1) cov.name = Cover_name cov.Select @cover = Cover.new(cov, items) dirt = @book.Worksheets(2) dirt.name = Directory_name dirt.Select @directory = Directory.new(dirt) @book.SaveAs("%s\\%s"%[@dir, Summary_file_name]) end def init_exist @book = @excel.Workbooks.Open("%s\\%s"%[@dir, Summary_file_name]) @cover = Cover.new(@book.Worksheets(Cover_name)) @cover.reconstruct @directory = Directory.new(@book.Worksheets(Directory_name)) @directory.reconstruct end end class Detail Rest_attr = "a" Step_attr = "b" Resp_attr = "c" def initialize dir @dir = dir @excel = WIN32OLE.new("excel.application") # @excel.Visible = true end def report results, filename book = @excel.Workbooks.Add sheet = book.Worksheets(1) sheet.Select# hyperlinks = sheet.Hyperlinks row = 2 results.each do |rlst_hash| step_cell = sheet.Range("#{Step_attr}#{row}") if rlst_hash[:step].is_a?(Hash) hyperlinks.Add(step_cell, rlst_hash[:step][:hyperlnk]) step_cell.Value = rlst_hash[:step][:text] else step_cell.Value = rlst_hash[:step] end rst_cell = sheet.Range("#{Resp_attr}#{row}") if rlst_hash[:response].is_a?(Hash) hyperlinks.Add(rst_cell, rlst_hash[:response][:hyperlnk]) rst_cell.Value = rlst_hash[:response][:text] else rst_cell.Value = rlst_hash[:response] end sheet.Range("#{Rest_attr}#{row}").Value = rlst_hash[:result] unless "Pass" == rlst_hash[:result] sheet.Range("#{Rest_attr}#{row}:#{Resp_attr}#{row}").Interior.ColorIndex = 3 end row += 1 end sheet.Columns(Rest_attr).ColumnWidth = 10 sheet.Columns(Step_attr).ColumnWidth = 120 sheet.Columns(Resp_attr).ColumnWidth = 120 path = "%s\\%s"%[@dir, filename] if File.file? path File.delete path end book.SaveAs(path) book.Close end def exit @excel.Quit end end end
class Sous < Formula desc "Sous tool for building and deploying at OpenTable" homepage "https://github.com/opentable/sous" # When the version of Sous changes, these two fields need to be updated version "0.1.7" sha256 "539ca446ecd9f931cb6eba24312f7dd1c724c4222140a701ababa3aef9265a1e" url "https://github.com/opentable/sous/releases/download/v#{version}/sous-darwin-amd64_#{version}.tar.gz" def install # ENV.deparallelize # if your formula fails when building in parallel bin.install "sous" end test do system "sous", "version" end end
# -*- encoding: utf-8 -*- # stub: handsoap 0.2.5 ruby lib Gem::Specification.new do |s| s.name = "handsoap".freeze s.version = "0.2.5" s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version= s.require_paths = ["lib".freeze] s.authors = ["Troels Knak-Nielsen".freeze] s.date = "2009-06-08" s.description = "Handsoap is a library for creating SOAP clients in Ruby".freeze s.email = "troelskn@gmail.com".freeze s.extra_rdoc_files = ["README.markdown".freeze] s.files = ["README.markdown".freeze, "VERSION.yml".freeze, "generators/handsoap/USAGE".freeze, "generators/handsoap/handsoap_generator.rb".freeze, "generators/handsoap/templates/DUMMY".freeze, "lib/handsoap.rb".freeze, "lib/handsoap/compiler.rb".freeze, "lib/handsoap/parser.rb".freeze, "lib/handsoap/service.rb".freeze, "lib/handsoap/xml_mason.rb".freeze] s.homepage = "http://github.com/troelskn/handsoap".freeze s.rdoc_options = ["--charset=UTF-8".freeze] s.rubygems_version = "2.6.14.1".freeze s.summary = "Handsoap is a library for creating SOAP clients in Ruby".freeze s.installed_by_version = "2.6.14.1" if s.respond_to? :installed_by_version if s.respond_to? :specification_version then s.specification_version = 2 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<nokogiri>.freeze, [">= 1.2.3"]) else s.add_dependency(%q<nokogiri>.freeze, [">= 1.2.3"]) end else s.add_dependency(%q<nokogiri>.freeze, [">= 1.2.3"]) end end
module API module V1 # API methods for monsters class Monsters < Grape::API resource :monsters do get '/' do @monsters = Monster.all end params do requires :monster_id, type: Integer, desc: 'Monster id' end get ':monster_id' do @monster = Monster.find(params[:monster_id]) end end end end end
# frozen_string_literal: true class TechniqueLink < ApplicationRecord acts_as_list scope: %i[linkable_type linkable_id], sequential_updates: true belongs_to :linkable, polymorphic: true validates :linkable_id, :linkable_type, :url, presence: true # validates :position, presence: true validates :title, length: { maximum: 64, allow_nil: true } validates :url, length: { in: 12..128 } validates :url, format: URI::DEFAULT_PARSER.make_regexp(%w[http https]) # validates :position, uniqueness: { scope: [:linkable_type,:linkable_id] } validates :url, uniqueness: { scope: %i[linkable_type linkable_id], case_sensitive: false } def label title.presence || url end end
require 'str_to_seconds' class Category < ApplicationRecord has_many :titles validates :name, presence: true validates :description, presence: true validates :loan_length_seconds, presence: true # before_save :update_titles_enabled def loan_length unless self.loan_length_seconds.nil? self.loan_length_seconds.to_human_time end end def loan_length=(length) self.loan_length_seconds = length.to_seconds end def enabled # the category is enabled if it has any enabled titles within it !titles.where(enabled: true).empty? end def popularity # return the total number of checkout records for all titles within the # category for sorting purposes (i.e. categories with most checkouts are # listed first in the checkout menu) @popularity = 0 Rails.cache.fetch("#{cache_key}/popularity", expires_in: 12.hours) do self.titles.each do |title| @popularity += title.popularity end end @popularity end ############################################################################# private ##################################################################### ############################################################################# # def update_titles_enabled # if enabled_changed? # titles.each do |title| # unless title.update(enabled: self.enabled) # raise RuntimeError.new("Unable to update enabled status on title: #{title.name}") # end # end # end # end end
module Api class SegmentsController < ApiController def index @segments = Segment.all render :index end def create @segment = Segment.new(segment_params) if @segment.save render json: @segment else render json: @segment.errors.full_messages end end def show @segment = Segment.find(params[:id]) render :show end private def segment_params params.require(:segment).permit(:song_id, :quote, :start_idx, :end_idx) end end end
require 'spec_helper' describe ArticlesController do context "unauthenticated" do it "should redirect to root path" do get :feed response.should redirect_to('/') flash[:notice].should == I18n.t("users.access.denied") end it "should be able to access index page" do get :index response.should be_success end end context "authenticated" do let(:admin) { create(:admin) } let(:article) { create(:article) } before do sign_in admin end describe "GET 'new'" do it "should be success" do get :new response.should be_success assigns(:article).should be_new_record end end describe "GET 'edit'" do it "should be success" do get :edit, id: article response.should be_success assigns(:article).should == article end end describe "PUT 'update'" do context "with valid param" do it "should be success" do put :update, id: article, article: { title: "updated article" } response.should redirect_to(articles_path) end end context "with invalid param" do it "should not update user" do put :update, id: article, article: { title: ''} response.should be_success response.should render_template('edit') end end end describe "POST 'create'" do context 'with valid params' do it "should be success" do post :create, article: { title: "New Article", url: "http://test.host" } Article.find_by_title("New Article") response.should redirect_to(articles_path) flash[:notice].should == I18n.t("articles.created") end end context "with invalid params" do it "should not create user" do lambda { post :create, article: {} response.should render_template('new') }.should_not change(Article, :count) end end end describe "DELETE 'destroy'" do it "should be success" do delete :destroy, id: article response.should redirect_to(articles_path) Article.should_not be_exists(article) end end describe "GET 'feed'" do it "should be success" do Article.should_receive(:build_from_params).with({ "url" => 'http://test.host' }).and_return(Article.new) get :feed, article: { url: 'http://test.host' }, format: :js response.should be_success end end end end
class Holiday < ApplicationRecord validates :name, presence: true validates :startDate, presence: true validates :endDate, presence: true end
require 'spec_helper' require_relative '../lib/grid_partition/algorithm/recursive_partition' require_relative '../lib/grid_partition/graph' describe GridPartition::Algorithm::RecursivePartition do include GridPartition::Algorithm::RecursivePartition before do continuable_nodes =[] (1..3).each do |i| (1..1).each do |j| continuable_nodes << GridPartition::Node::new(i,j,1.0) end end @continuable_graph = GridPartition::Graph::new(continuable_nodes) @uncontinuable_graph1 = @continuable_graph - @continuable_graph @uncontinuable_graph2 = @continuable_graph - [GridPartition::Node.new(1,1,1.0),GridPartition::Node.new(2,1,1.0)] end describe "#continuable?" do it "should return false if graph's longer side < 2" do continuable?(@continuable_graph).should be(true) continuable?(@uncontinuable_graph1).should be(false) continuable?(@uncontinuable_graph2).should be(false) end end describe "#evaluate" do it "should correctly calculate" do g1 = GridPartition::Graph.new([GridPartition::Node.new(1,2,1.0)]) g2 = GridPartition::Graph.new([ GridPartition::Node.new(2,3,5.0), GridPartition::Node.new(1,4,3.0) ]) evaluate(g1,g2).should be == (1.0/1 - 8.0/2).abs evaluate(g1,g1).should be == (1.0/1 - 1.0/1).abs evaluate(g2,g2).should be == (8.0/2 - 8.0/2).abs end it "should raise error when empty graph given" do g1 = GridPartition::Graph.new([GridPartition::Node.new(1,2,1.0)]) expect { evaluate(g1,@uncontinuable_graph1) }.to raise_error expect { evaluate(@uncontinuable_graph1,g1) }.to raise_error end end describe "#execute" do before do #12nodes #|_|x|_|x|x| #|x|x|x|x|_| #|x|_|x|_|_| #|_|x|_|x|x| # @arbitrary_nodes=[ GridPartition::Node::new(1,2,1.0), GridPartition::Node::new(1,3,1.0), GridPartition::Node::new(2,1,1.0), GridPartition::Node::new(2,2,1.0), GridPartition::Node::new(2,4,1.0), GridPartition::Node::new(3,2,1.0), GridPartition::Node::new(3,3,1.0), GridPartition::Node::new(4,1,1.0), GridPartition::Node::new(4,2,1.0), GridPartition::Node::new(4,4,1.0), GridPartition::Node::new(5,1,1.0), GridPartition::Node::new(5,4,1.0) ] @arbitrary_graph = GridPartition::Graph::new(@arbitrary_nodes) end it "should raise if threshold is not implicitly set" do result =[] expect{ GridPartition::Algorithm::RecursivePartition::execute(@arbitrary_graph,result) }.to raise_error end it "should return non-duplicated result" do GridPartition::Algorithm::RecursivePartition::threshold = Float::INFINITY result = [] GridPartition::Algorithm::RecursivePartition::execute(@arbitrary_graph,result) expected_graph = GridPartition::Graph::new() result.each do |e| expected_graph.merge(e) end expected_graph.size.should be == @arbitrary_nodes.size expected_graph.should be == @arbitrary_graph # GridPartition::Graph::new(result.map{|e| e}).size.should eq(arbitrary_nodes.size) end end end
class Api::PostLikesController < ApplicationController before_action :require_logged_in before_action :require_friendship, only: [:create] def create @post_like = PostLike.new( user_id: current_user.id, post_id: post_like_params[:post_id] ) if @post_like.save render :show else render json: @post_like.errors, status: 422 end end def destroy @post_like = PostLike.find(params[:id]) if @post_like.user_id == current_user.id @post_like.destroy render :show else render json: ["not your like to unlike"], status: 401 end end private def post_like_params params.require(:post_like).permit(:post_id) end def require_friendship friend = Post.find(post_like_params[:post_id]).author if !current_user.friends.exists?(friend.id) && friend.id != current_user.id render json: ["can't like/unlike if not friend"], status: 401 end end end
# == Schema Information # # Table name: routes # # id :integer not null, primary key # name :string(255) # latitude :float # longitude :float # created_at :datetime not null # updated_at :datetime not null # user_id :integer # difficulty :string(255) # latitude2 :float # longitude2 :float # distance :integer # type_distance :string(255) # timeroute :integer # type_timeroute :string(255) # class Route < ActiveRecord::Base attr_accessible :latitude, :longitude, :latitude2, :longitude2, :name, :difficulty, :distance, :type_distance, :timeroute, :type_timeroute # ogni itinerario è associato a uno specifico utente belongs_to :user # ordine decrescente della data di creaz per il get degli itinerari default_scope order: 'routes.created_at DESC' # ogni itinerario può avere molte user_route_relationships # definiamo esplicitamente la chiave esterna e facciamo in modo che se l'itinerario viene eliminato, vengono # eliminate anche le sue user_route_relationships has_many :user_route_relationships, foreign_key: 'route_id', dependent: :destroy # ogni utente può avere molte "reverse" user_route_relationships has_many :reverse_user_route_relationships, foreign_key: 'route_id', class_name: 'UserRouteRelationship', dependent: :destroy # ogni itinerario può avere molti follower attraverso reverse user_route_relationships has_many :followers, through: :reverse_user_route_relationships # user_id e coordinate sempre presenti validates :user_id, :latitude, :longitude, :latitude2, :longitude2, :presence => true # ogni itinerario può avere più comment_routes, e se viene cancellato anche i suoi commenti vengono rimossi has_many :comment_routes, dependent: :destroy # name sempre presente e unico validates :name, :presence => true, :uniqueness => true # coordinate uniche (a coppia) validates :longitude, :uniqueness => {:scope => :latitude} validates :longitude2, :uniqueness => {:scope => :latitude2} #distanza percorsa e tempo validates :distance, :presence => true, :numericality => true validates :timeroute, :presence => true, :numericality => true end
Facter.add(:wrecked) do setcode do Dir.glob('/var/spool/wrecked/*.wreck').collect {|e| File.basename(e, '.wreck')} end end
module Imdb # Represents a Movie on IMDB.com class Movie attr_accessor :id, :url, :title # Initialize a new IMDB movie object with it's IMDB id (as a String) # # movie = Imdb::Movie.new("0095016") # # Imdb::Movie objects are lazy loading, meaning that no HTTP request # will be performed when a new object is created. Only when you use an # accessor that needs the remote data, a HTTP request is made (once). # # params: # attributes a hash of Symbol => value # attributes[:locale] the locale to use for the DB query def initialize(imdb_id, attributes={}) @id = imdb_id @url = "http://www.imdb.com/title/tt#{imdb_id}/" attributes={:title => attributes} if attributes.kind_of?(String) @locale = attributes.delete(:locale) @attributes=attributes @attributes[:title] = @attributes[:title].gsub(/"/, "") if @attributes[:title] end def reload @attributes={} @document=nil self end # Returns an array with cast members def cast_members document.xpath("//*[@class='cast_list']//*[@itemprop='actor']//*[@itemprop='name']").map { |elem| elem.text.imdb_unescape_html } rescue [] end def cast_member_ids ids=document.xpath("//*[@class='cast_list']//*[@itemprop='actor']//*[@itemprop='url']").map { |elem| elem['href'] =~ %r{^/name/(nm\d+)} $1 } rescue [] ids end # Returns the name(s) of the director(s) def director document.xpath("//*[@itemprop='director']//*[@itemprop='name']").map { |elem| elem.text.imdb_unescape_html } rescue [] end # Returns an array of genres (as strings) def genres document.xpath("//*[@itemprop='genre']//a").map { |elem| elem.text.imdb_unescape_html } rescue [] end # Returns an array of languages as strings. def languages #document.xpath("h4[text()='Language:'] ~ a[@href*='/language/']").map { |link| link.innerHTML.imdb_unescape_html } document.xpath("//h4[normalize-space(.)='Language:']").first.parent.xpath("a"). map { |link| link.text.imdb_unescape_html } rescue [] end # Returns the duration of the movie in minutes as an integer. def length document.xpath("//h4[normalize-space(.)='Runtime:']").first.next_element.text.to_i rescue nil end # Returns a string containing the plot. def plot sanitize_plot(document.xpath("//*[@itemprop='description']").first.text.imdb_unescape_html) rescue nil end # Returns a string containing the URL to the movie poster. def poster src = document.xpath("//td[@id='img_primary']//img") return nil if src.empty? src=src.first['src'] case src when /^(http:.+@@)/ $1 + '.jpg' when /^(http:.+?)\.[^\/]+$/ $1 + '.jpg' end end # Returns a float containing the average user rating def rating document.css(".star-box-giga-star").text.imdb_unescape_html.to_f rescue nil end # Returns a string containing the tagline def tagline document.xpath("//h4[text()='Taglines:']").first.next_sibling.text.imdb_unescape_html rescue nil end # Returns a string containing the mpaa rating and reason for rating #def mpaa_rating # document.search("h4[text()*='Motion Picture Rating']").first.next_sibling.to_s.strip.imdb_unescape_html rescue nil #end # Returns a string containing the title def title attr(:title) do document.xpath("//*[@class='header']//*[@class='itemprop' and @itemprop='name']").text.imdb_unescape_html end end def original_title attr(:original_title) do document.xpath("//*[@class='header']//*[@class='title-extra' and @itemprop='name']").children.first.text.imdb_unescape_html end end # Returns an integer containing the year (CCYY) the movie was released in. def year attr(:year) do document.xpath('//*[@class="header"]//a[starts-with(@href,"/year/")]').text.imdb_unescape_html.to_i end end # Returns release date for the movie. def release_date sanitize_release_date(document.xpath("//h4[normalize-space(.)='Release Date:']").first.next.text) rescue nil end private # Returns a new Hpricot document for parsing. def document @document ||= Nokogiri::HTML(Imdb::Utils.get_page("/title/tt#{@id}/", @locale)) end # Convenience method for search def self.search(query) Imdb::Search.new(query).movies end def self.top_250 Imdb::Top250.new.movies end def sanitize_plot(the_plot) the_plot.gsub(/\s*See full summary.*/, '') end def sanitize_release_date(date) date.strip.imdb_unescape_html.gsub("\n", ' ') end def attr(name, on_fail=nil) return @attributes[name] if @attributes.has_key?(name) #@attributes[name] = yield @attributes[name] = (yield rescue on_fail) end end # Movie end # Imdb
require 'yaml' require 'pry' MESSAGES = YAML.load_file('loan_calculator_messages.yml') def prompt(message) puts ">> #{message}" end def valid_whole?(loan) /^\d+$/.match?(loan) && loan.to_i >= 1 end def valid_decimal?(amount) amount.to_f.to_s == amount && amount.to_f > 0 end def monthly_apr(rate) rate.to_f/ 100 / 12 end def clear system('clear') end loan_amount = nil apr = nil months = nil prompt(MESSAGES['welcome']) prompt(MESSAGES["welcome2"]) loop do loop do prompt(MESSAGES['loan_amount']) loan_amount = gets.chomp break if valid_whole?(loan_amount) || valid_decimal?(loan_amount) prompt(MESSAGES['loan_amount_error']) end prompt"So the loan amount is $#{loan_amount}." loop do prompt(MESSAGES['apr']) apr = gets.chomp break if valid_decimal?(apr) || valid_whole?(apr) prompt(MESSAGES['apr_error']) end prompt"Your APR is #{apr}%" loop do prompt(MESSAGES['duration']) months = gets.chomp break if valid_whole?(months) prompt(MESSAGES['duration_invalid']) prompt(MESSAGES['month_equation']) end month_interest = monthly_apr(apr) loan_amount = loan_amount.to_i total = loan_amount * (month_interest / (1 - (1 + month_interest)**(-months.to_i))) total = total.to_f.round(2) prompt"Your initial loan of $#{loan_amount}, at an annual rate of #{apr}% for" prompt"#{months} months will result in a monthly payment of $#{total}." prompt(MESSAGES['calculate_again?']) again = gets.chomp.upcase! break if again.start_with?("N") end prompt(MESSAGES['goodbye'])
# Implementar en este fichero la clase para crear objetos racionales require "./gcd.rb" class Fraccion attr_reader :numerador, :denominador #metodo inicializa fraccion def initialize(numerador, denominador) @numerador= numerador @denominador = denominador forma_reducida end def to_s puts "#{@numerador} / #{@denominador}" end def forma_reducida divisor = gcd(numerador, denominador) numerador = @numerador / divisor denominador = @denominador / divisor # puts "#{numerador} / #{denominador}" end def suma(r) if r.is_a? Fraccion resultado = Fraccion.new(@numerador + r.numerador, @denominador + r.denominador) #tienen el mismo divisor else resultado = Fraccion.new(@numerador + @denominador*r, @denominador) end end def resta(r) if r.is_a? Fraccion resultado = Fraccion.new(@numerador - r.numerador , @denominador - r.denominador) else resultado = Fraccion.new(@numerador - @denominador*r, @denominador) end end def producto(r) if r.is_a? Fraccion resultado = Fraccion.new(@numerador*r.numerador, @denominador*r.denominador) else resultado = Fraccion.new(@numerador*r, @denominador) end end def division(r) if r.is_a? Fraccion resultado = Fraccion.new(@numerador*r.denominador, @denominador*r.numerador) else resultado = Fraccion.new(@numerador, @denominador*r) end end end #end de la clase
require 'spec_helper' describe Restaurant do it 'is not valid without a name' do restaurant = Restaurant.new(name:nil) expect(restaurant).to have(2).errors_on(:name) expect(restaurant.valid?).to eq false end it 'is not valid without an address' do restaurant = Restaurant.new(address:nil) expect(restaurant).to have(1).errors_on(:address) end it 'is not valid without a cuisine' do restaurant = Restaurant.new(cuisine:nil) expect(restaurant).to have(1).errors_on(:cuisine) expect(restaurant.valid?).to eq false end end describe '#average_rating' do let(:restaurant) {Restaurant.create(name: 'KFC', address: '1 High Street', cuisine: 'chicken')} it 'intially returns N/A' do expect(restaurant.average_rating).to eq 'N/A' end context '1 review' do before {restaurant.reviews.create(rating: 3)} it 'returns the score of that review' do expect(restaurant.average_rating).to eq 3 end end context '> 1 review' do before do restaurant.reviews.create(rating: 3) restaurant.reviews.create(rating: 5) end it 'returns the score of that review' do expect(restaurant.average_rating).to eq 4 end end context 'non-integer average' do before do restaurant.reviews.create(rating: 2) restaurant.reviews.create(rating: 5) it 'does not round up or down' do expect(retsaurant.average_rating).to eq 3.5 end end end end
require 'binary_struct' require 'miq_unicode' require 'fs/ntfs/index_node_header' require 'fs/ntfs/directory_index_node' require 'fs/ntfs/index_record_header' module NTFS using ManageIQ::UnicodeString # # INDEX_ROOT - Attribute: Index root (0x90). # # NOTE: Always resident. # # This is followed by a sequence of index entries (INDEX_ENTRY structures) # as described by the index header. # # When a directory is small enough to fit inside the index root then this # is the only attribute describing the directory. When the directory is too # large to fit in the index root, on the other hand, two additional attributes # are present: an index allocation attribute, containing sub-nodes of the B+ # directory tree (see below), and a bitmap attribute, describing which virtual # cluster numbers (vcns) in the index allocation attribute are in use by an # index block. # # NOTE: The root directory (FILE_root) contains an entry for itself. Other # directories do not contain entries for themselves, though. # ATTRIB_INDEX_ROOT = BinaryStruct.new([ 'L', 'type', # Type of the indexed attribute. Is FILE_NAME for directories, zero # for view indexes. No other values allowed. 'L', 'collation_rule', # Collation rule used to sort the index entries. If type is $FILE_NAME, # this must be COLLATION_FILE_NAME 'L', 'index_block_size', # Size of index block in bytes (in the index allocation attribute) 'C', 'clusters_per_index_block', # Size of index block in clusters (in the index allocation attribute), # when an index block is >= than a cluster, otherwise sectors per index block 'a3', nil, # Reserved/align to 8-byte boundary ]) # Here follows a node header. SIZEOF_ATTRIB_INDEX_ROOT = ATTRIB_INDEX_ROOT.size class IndexRoot DEBUG_TRACE_FIND = false && $log CT_BINARY = 0x00000000 # Binary compare, MSB is first (does that mean big endian?) CT_FILENAME = 0x00000001 # UNICODE strings. CT_UNICODE = 0x00000002 # UNICODE, upper case first. CT_ULONG = 0x00000010 # Standard ULONG, 32-bits little endian. CT_SID = 0x00000011 # Security identifier. CT_SECHASH = 0x00000012 # First security hash, then security identifier. CT_ULONGS = 0x00000013 # Set of ULONGS? (doc is unclear - indicates GUID). def self.create_from_header(header, buf, bs) return IndexRoot.new(buf, bs) if header.containsFileNameIndexes? $log.debug("Skipping #{header.typeName} for name <#{header.name}>") if $log nil end attr_reader :type, :nodeHeader, :index, :indexAlloc def initialize(buf, boot_sector) log_prefix = "MIQ(NTFS::IndexRoot.initialize)" raise "#{log_prefix} Nil buffer" if buf.nil? raise "#{log_prefix} Nil boot sector" if boot_sector.nil? buf = buf.read(buf.length) if buf.kind_of?(DataRun) @air = ATTRIB_INDEX_ROOT.decode(buf) buf = buf[SIZEOF_ATTRIB_INDEX_ROOT..-1] # Get accessor data. @type = @air['type'] @collation_rule = @air['collation_rule'] @byteSize = @air['index_block_size'] @clusterSize = @air['size_of_index_clus'] @boot_sector = boot_sector # Get node header & index. @foundEntries = {} @indexNodeHeader = IndexNodeHeader.new(buf) @indexEntries = cleanAllocEntries(DirectoryIndexNode.nodeFactory(buf[@indexNodeHeader.startEntries..-1])) @indexAlloc = {} end def to_s @type.to_s end def allocations=(indexAllocations) @indexAllocRuns = [] if @indexNodeHeader.hasChildren? && indexAllocations indexAllocations.each { |alloc| @indexAllocRuns << [alloc.header, alloc.data_run] } end @indexAllocRuns end def bitmap=(bmp) if @indexNodeHeader.hasChildren? @bitmap = bmp.data.unpack("b#{bmp.length * 8}") unless bmp.nil? end @bitmap end # Find a name in this index. def find(name) log_prefix = "MIQ(NTFS::IndexRoot.find)" name = name.downcase $log.debug "#{log_prefix} Searching for [#{name}]" if DEBUG_TRACE_FIND if @foundEntries.key?(name) $log.debug "#{log_prefix} Found [#{name}] (cached)" if DEBUG_TRACE_FIND return @foundEntries[name] end found = findInEntries(name, @indexEntries) if found.nil? # Fallback to full directory search if not found $log.debug "#{log_prefix} [#{name}] not found. Performing full directory scan." if $log found = findBackup(name) $log.send(found.nil? ? :debug : :warn, "#{log_prefix} [#{name}] #{found.nil? ? "not " : ""}found in full directory scan.") if $log end found end # Return all names in this index as a sorted string array. def globNames @globNames = globEntries.collect { |e| e.namespace == NTFS::FileName::NS_DOS ? nil : e.name.downcase }.compact if @globNames.nil? @globNames end def findInEntries(name, entries) log_prefix = "MIQ(NTFS::IndexRoot.findInEntries)" if @foundEntries.key?(name) $log.debug "#{log_prefix} Found [#{name}] in #{entries.collect { |e| e.isLast? ? "**last**" : e.name.downcase }.inspect}" if DEBUG_TRACE_FIND return @foundEntries[name] end $log.debug "#{log_prefix} Searching for [#{name}] in #{entries.collect { |e| e.isLast? ? "**last**" : e.name.downcase }.inspect}" if DEBUG_TRACE_FIND # TODO: Uses linear search within an index entry; switch to more performant search eventually entries.each do |e| $log.debug "#{log_prefix} before [#{e.isLast? ? "**last**" : e.name.downcase}]" if DEBUG_TRACE_FIND if e.isLast? || name < e.name.downcase $log.debug "#{log_prefix} #{e.hasChild? ? "Sub-search in child vcn [#{e.child}]" : "No sub-search"}" if DEBUG_TRACE_FIND return e.hasChild? ? findInEntries(name, getIndexAllocEntries(e.child)) : nil end end $log.debug "#{log_prefix} Did not find [#{name}]" if DEBUG_TRACE_FIND nil end def findBackup(name) globEntriesByName[name] end def getIndexAllocEntries(vcn) unless @indexAlloc.key?(vcn) log_prefix = "MIQ(NTFS::IndexRoot.getIndexAllocEntries)" begin raise "not allocated" if @bitmap[vcn, 1] == "0" header, run = @indexAllocRuns.detect { |h, _r| vcn >= h.specific['first_vcn'] && vcn <= h.specific['last_vcn'] } raise "header not found" if header.nil? raise "run not found" if run.nil? run.seekToVcn(vcn - header.specific['first_vcn']) buf = run.read(@byteSize) raise "buffer not found" if buf.nil? raise "buffer signature is expected to be INDX, but is [#{buf[0, 4].inspect}]" if buf[0, 4] != "INDX" irh = IndexRecordHeader.new(buf, @boot_sector.bytesPerSector) buf = irh.data[IndexRecordHeader.size..-1] inh = IndexNodeHeader.new(buf) @indexAlloc[vcn] = cleanAllocEntries(DirectoryIndexNode.nodeFactory(buf[inh.startEntries..-1])) rescue => err $log.warn "#{log_prefix} Unable to read data from index allocation at vcn [#{vcn}] because <#{err.message}>\n#{dump}" if $log @indexAlloc[vcn] = [] end end @indexAlloc[vcn] end def cleanAllocEntries(entries) cleanEntries = [] entries.each do |e| if e.isLast? || !(e.contentLen == 0 || (e.refMft[1] < 12 && e.name[0, 1] == "$")) cleanEntries << e # Since we are already looping through all entries to clean # them we can store them in a lookup for optimization @foundEntries[e.name.downcase] = e unless e.isLast? end end cleanEntries end def globEntries return @globEntries unless @globEntries.nil? # Since we are reading all entries, retrieve all of the data in one call @indexAllocRuns.each do |_h, r| r.rewind r.read(r.length) end @globEntries = globAllEntries(@indexEntries) end def globEntriesByName log_prefix = "MIQ(NTFS::IndexRoot.globEntriesByName)" if @globbedEntriesByName $log.debug "#{log_prefix} Using cached globEntries." if DEBUG_TRACE_FIND return @foundEntries end $log.debug "#{log_prefix} Initializing globEntries:" if DEBUG_TRACE_FIND globEntries.each do |e| $log.debug "#{log_prefix} #{e.isLast? ? "**last**" : e.name.downcase}" if DEBUG_TRACE_FIND @foundEntries[e.name.downcase] = e end @globbedEntriesByName = true @foundEntries end def globAllEntries(entries) ret = [] entries.each do |e| ret += globAllEntries(getIndexAllocEntries(e.child)) if e.hasChild? ret << e unless e.isLast? end ret end def dump out = "\#<#{self.class}:0x#{'%08x' % object_id}>\n" out << " Type : 0x#{'%08x' % @type}\n" out << " Collation Rule : #{@collation_rule}\n" out << " Index size (bytes) : #{@byteSize}\n" out << " Index size (clusters): #{@clusterSize}\n" @indexEntries.each { |din| out << din.dump } out << "---\n" out end end end # module NTFS
class StripeCharge def initialize(stripe_id) @stripe_id = stripe_id end def on_succeeded self.invoice.on_successful_payment end def invoice_id self.charge.invoice end def invoice return @invoice if @invoice @invoice = StripeInvoice.new self.invoice_id, self.card_description, self.card_charged_at end def card_description card = self.charge.card "#{card.type} (last 4 digits: #{card.last4})" end def card_charged_at self.charge.created end def charge return @charge if @charge @charge = Stripe::Charge.retrieve @stripe_id end end
module Ricer::Plug::Params class ServerUrlParam < UrlParam def schemes ['irc', 'ircs'] end end end
require_relative 'tax' require_relative 'order' require 'yaml' class OrderProcessor attr_accessor :order_lines, :total_tax, :total_items_cost, :args, :tax def initialize (args, config_file) @tax = Tax.new(YAML.load_file(config_file)) @args = args end def get_order @order_lines = Order::OrderReader.read_order(@args) end def process_order @total_tax = 0 @total_items_cost = 0 @order_lines.each do |line| @total_tax += line.calculate_line_tax (@tax) @total_items_cost += line.total end end def print_reciept @order_lines.each do |line| line.print_order_line end print_tax_total print_order_total end def print_tax_total puts "Sales Taxes: #{sprintf( "%0.02f",@total_tax)}" end def print_order_total puts "Total: #{sprintf( "%0.02f", @total_tax + @total_items_cost)}" end end
# frozen_string_literal: true module Dotloop module Models class Contact include Virtus.model attribute :address attribute :city attribute :country attribute :email attribute :fax attribute :first_name attribute :home attribute :id, Integer attribute :last_name attribute :office attribute :state attribute :zip_code attr_accessor :client end end end
class PigLatinizer def piglatinize(input) #take in a string #split it by spaces #iterate over the array #for each word, take first letter and append it to the end and add 'ay' #if it begins with a vowel, don't shift first letter and append 'way' #then join with spaces words = input.split(' ') words.map do |word| if word[0].index(/[aeiouAEIOU]/).nil? parts = word.split(/([aeiouAEIOU].*)/) "#{parts[1]}#{parts[0]}ay" else "#{word}way" end end.join(' ') end def to_pig_latin(input) piglatinize(input) end end
require Rails.root.join('lib', 'rails_admin', 'book_report') RailsAdmin::Config::Actions.register(RailsAdmin::Config::Actions::BookReport) RailsAdmin.config do |config| config.main_app_name = ["Lib Fácil", ""] ### Popular gems integration ## == Devise == config.authenticate_with do warden.authenticate! scope: :user end config.current_user_method(&:current_user) ## == Cancan == config.authorize_with :cancan config.actions do dashboard # mandatory index # mandatory new show edit delete show_in_app end config.model Author do visible false end config.model Author do create do field :name end edit do field :name end end config.model Location do visible false end config.model Location do create do field :name end edit do field :name end end config.model Loan do navigation_icon 'fa fa-book' weight -2 create do field :book do help 'Pesquisar por nome ou código' associated_collection_cache_all false associated_collection_scope do Proc.new { |scope| scope = scope.where(status: true) } end end field :client field :status, :enum do queryable false # if your model has a method that sends back the options: enum_method do :status_enum end end field :date do strftime_format do '%d-%m-%Y' end end field :note field :user_id, :hidden do default_value do bindings[:view]._current_user.id end end end edit do field :book field :client field :status, :enum do queryable false # if your model has a method that sends back the options: enum_method do :status_enum end end field :date do strftime_format do '%d-%m-%Y' end end field :note field :user_id, :hidden do default_value do bindings[:view]._current_user.id end end end list do field :book do queryable true end field :client field :status, :enum do enum_method do :status_enum end end field :date do queryable false strftime_format do '%d-%m-%Y' end end field :note end end config.model Book do navigation_icon 'fa fa-leanpub' weight -3 create do field :title field :sinopse field :author field :location end edit do field :title field :sinopse field :author field :location end list do field :title field :location do queryable true searchable [:name, :id] end field :author do queryable true searchable [:name, :id] end end end config.model User do navigation_icon 'fa fa-user' weight -1 create do field :name field :kind field :status field :email field :password field :password_confirmation end edit do field :name field :kind field :status field :email field :password field :password_confirmation end list do field :name field :kind field :status field :email end end end
class RemoveColumnFacebookIdFromCampaign < ActiveRecord::Migration[5.0] def change remove_column :campaigns, :facebook_campaign_id end end
# frozen_string_literal: true require 'time' require_relative 'analyzable' class SalesAnalyst include Analyzable attr_reader :items def initialize(items, merchants, customers, invoices, invoice_items, transactions) @items = items @merchants = merchants @customers = customers @invoices = invoices @invoice_items = invoice_items @transactions = transactions end def merchants_with_high_item_count sd = average_items_per_merchant_standard_deviation mean = average_items_per_merchant @merchants.all.find_all do |merchant| @items.find_all_by_merchant_id(merchant.id).length > (sd + mean) end end def golden_items average = average_average_price_per_merchant sum = @items.all.sum do |item| (item.unit_price - average) ** 2 end sum /= (@items.all.length - 1) sd = Math.sqrt(sum) @items.all.select do |item| item.unit_price > ((sd * 2) + average) end end def top_merchants_by_invoice_count mean = average_invoices_per_merchant sd = average_invoices_per_merchant_standard_deviation @merchants.all.select do | merchant | @invoices.find_all_by_merchant_id(merchant.id).length > (mean + (sd * 2)) end end def bottom_merchants_by_invoice_count mean = average_invoices_per_merchant sd = average_invoices_per_merchant_standard_deviation @merchants.all.select do | merchant | @invoices.find_all_by_merchant_id(merchant.id).length < (mean - (sd * 2)) end end def invoice_status(status) status_count = Hash.new(0) @invoices.all.each do | invoice | status_count[invoice.status] += 1 end ((100.0 * status_count[status]) / @invoices.all.length).round(2) end def invoice_paid_in_full?(invoice_id) results = [] @transactions.find_all_by_invoice_id(invoice_id).each do |transaction| if transaction.result == :success results << true else results << false end end results.any?(true) end def top_revenue_earners(num = 20) merchant_total_revenue_hash = Hash.new(0) @invoices.all.each do |invoice| merchant_total_revenue_hash[invoice.merchant_id] += invoice_total(invoice.id) end array = merchant_total_revenue_hash.sort_by do |merchant_id, total| - total end array.first(num).map do |merchant_id_array| @merchants.find_by_id(merchant_id_array[0]) end end def merchants_with_only_one_item merchant_array = [] @merchants.all.each do |merchant| if @items.find_all_by_merchant_id(merchant.id).length == 1 merchant_array << merchant end end merchant_array end def merchants_with_only_one_item_registered_in_month(month) merchant_month_array = [] @merchants.all.each do |merchant| if merchant.created_at.strftime('%B') == month merchant_month_array << merchant end end merchant_array = [] merchant_month_array.each do |merchant| if @items.find_all_by_merchant_id(merchant.id).length == 1 merchant_array << merchant end end merchant_array end def merchants_with_pending_invoices @invoices.all.map do |invoice| if invoice_paid_in_full?(invoice.id) == false @merchants.find_by_id(invoice.merchant_id) end end.uniq.compact end def invoice_items_for_merchant(merchant_id) items_for_merchant = @items.find_all_by_merchant_id(merchant_id) items_for_merchant.map do |item| @invoice_items.find_all_by_item_id(item.id) end.flatten end def invoice_items_by_quantity(merchant_id) invoice_items_for_merchant(merchant_id).each_with_object({}) do |invoice_item, items_by_quantity| if items_by_quantity[invoice_item.item_id] items_by_quantity[invoice_item.item_id] += invoice_item.quantity else items_by_quantity[invoice_item.item_id] = invoice_item.quantity end end end def most_sold_item_for_merchant(merchant_id) invoice_array = invoice_items_by_quantity(merchant_id).sort_by do |item_id, quantity| - quantity end if invoice_array[0][1] != invoice_array[1][1] [@items.find_by_id(invoice_array[0][0])] else invoice_array.map do |array| if invoice_array[0][1] == array[1] @items.find_by_id(array[0]) end end end end def invoice_items_by_revenue(merchant_id) invoice_items_for_merchant(merchant_id).each_with_object({}) do |invoice_item, items_by_revenue| if items_by_revenue[invoice_item.item_id] items_by_revenue[invoice_item.item_id] += (invoice_item.quantity * invoice_item.unit_price) else items_by_revenue[invoice_item.item_id] = (invoice_item.quantity * invoice_item.unit_price) end end end def best_item_for_merchant(merchant_id) invoice_array = invoice_items_by_revenue(merchant_id).sort_by do |item_id, revenue| - revenue end @items.find_by_id(invoice_array[0][0]) end def top_buyers(num = 20) customer_total_purchase_hash = Hash.new(0) @invoices.all.each do |invoice| customer_total_purchase_hash[invoice.customer_id] += invoice_total(invoice.id) end array = customer_total_purchase_hash.sort_by do |merchant_id, total| - total end array.first(num).map do |customer_id_array| @customers.find_by_id(customer_id_array[0]) end end def top_merchant_for_customer(customer_id) invoice_array = @invoices.find_all_by_customer_id(customer_id) invoice_item_hash = {} invoice_array.each do |invoice| invoice_item_hash[invoice.id] = @invoice_items.find_all_by_invoice_id(invoice.id) end invoice_hash = {} invoice_item_hash.each do |invoice_id, invoice_item_array| invoice_hash[invoice_id] = invoice_item_array.sum {|item| item.quantity} end pair = invoice_hash.max_by do |key, value| value end @merchants.find_by_id(@invoices.find_by_id(pair[0]).merchant_id) end end
require "bundler/gem_tasks" require 'appraisal' require "rspec/core/rake_task" RSpec::Core::RakeTask.new(:spec) desc 'Default: run unit tests.' task default: [:all] desc 'Test the paperclip plugin under all supported Rails versions.' task :all do |t| ENV['RAILS_ENV'] ||= 'test' puts 'Create database' Dir.chdir('spec/dummy') do if Gem.loaded_specs['railties'].version >= Gem::Version.new('5.0.0') system('bundle exec rake db:environment:set RAILS_ENV=test') system({ 'RAILS_ENV' => 'test' }, 'bundle exec rake db:reset') else system({ 'RAILS_ENV' => 'test' }, 'bundle exec rake db:reset') end end puts 'rake spec' ENV['QUERY_CACHE_ENABLED'] = nil Rake::Task[:spec].execute puts 'QUERY_CACHE_ENABLED=1 rake spec' ENV['QUERY_CACHE_ENABLED'] = '1' Rake::Task[:spec].execute end
class AddDoneColumnToGoals < ActiveRecord::Migration[5.0] def change add_column :goals, :done, :boolean, default: :false add_column :goals, :expected_completion_day, :date # Expected Completion Day end end
class Api::V1::FavoriteController < ApplicationController def index if listing_params[:api_key].present? && user(listing_params).present? favorite_locations = user(listing_params).favorites.each do |favorite| favorite.location end listing_location = FavoriteLocation.new(favorite_locations) render json: FavoriteLocationSerializer.new(listing_location) else render status: 401 end end def create if favorite_params[:api_key].present? && user(favorite_params).present? render json: FavoriteSerializer.new(add_favorite), status: 200 else render status: 401 end end private def favorite_params params.permit(:api_key, :location) end def listing_params params.permit(:api_key) end def user(params) User.find_by_api_key(params[:api_key]) end def add_favorite user(favorite_params).favorites.find_or_create_by(location: favorite_params[:location]) end end
require 'capistrano/cli' require 'fileutils' class Capfile def initialize(path, stage = nil) @path = path @cap = load(stage) end def tasks cap_tasks end def stages cap_stages end def variables @cap.variables end private def load(stage) def build_query(stage) if stage.nil? return %W(-f Capfile -Xx -l STDOUT) else return %W(-f Capfile -Xx -l STDOUT #{stage}) end end FileUtils.chdir @path do return Capistrano::CLI.parse(build_query(stage)).execute! end end def cap_tasks @cap.task_list(:all).sort_by(&:fully_qualified_name).map {|task| { :name => task.fully_qualified_name, :description => task.description, :brief_description => task.brief_description } } end def cap_stages def filter(variables) variables.select { |key, name| name.is_a?(String) } end if !@cap.variables[:stages].nil? @cap.variables[:stages].map do |stage| { :name => stage, :variables => filter(Capfile.new(@path, stage).variables) } end else [{ :name => "default", :variables => filter(@cap.variables) }] end end end
def select_letter(sentence, letter) selected = '' counter = 0 loop do break if counter == sentence.size current_letter = sentence[counter] selected << current_letter if current_letter == letter counter += 1 end selected end question = 'How many times does a particular character appear in this sentence?' p select_letter(question, 'a').size p select_letter(question, 't').size p select_letter(question, 'z').size
class PublicController < ApplicationController layout 'public' before_filter :load_nav before_filter :get_master_user def index #renders index template end def show @page = Page.where(:title => params[:id], :visible => true).first #TODO: does the visibile part make this error-prone? @items = Item.sort.visible.where(:page_id => @page.id) redirect_to(:root) unless @page end private def get_master_user # since this app is designed for one and only one user, this is acceptable, if inelegant @master_user = User.find_by_username("ianm") end end
class GigSong < ApplicationRecord belongs_to :gig belongs_to :song scope :by_date, -> { order(date: :asc) } scope :unique, -> { group(:song_id) } scope :not_over, -> { where("date > ?", DateTime.now)} def self.search(search) if search Song.find_by(name: search) end end def song_name=(name) self.song = Song.find_or_create_by(name: name) unless name == "" end def song_name self.song ? self.song.name : nil end def version self.original ? "Original Version" : "#{self.gig.band.name} Version" end def add_notes if self.notes != "" "- Notes: #{self.notes}" end end def gs_date self.gig.date end def show_date gs_date.strftime("%a %B %d, %Y") end end
class Api::V1::InviteNotificationsController < Api::V1::BaseController before_action :set_invite_notification, only: [:show, :update, :destroy] # GET /invite_notifications def index @invite_notifications = InviteNotification.all render json: @invite_notifications end # GET /invite_notifications/1 def show render json: @invite_notification end # POST /invite_notifications def create @invite_notification = InviteNotification.new(invite_notification_params) if @invite_notification.save render json: @invite_notification, status: :created, location: @invite_notification else render json: @invite_notification.errors, status: :unprocessable_entity end end # PATCH/PUT /invite_notifications/1 def update if @invite_notification.update(invite_notification_params) render json: @invite_notification else render json: @invite_notification.errors, status: :unprocessable_entity end end # DELETE /invite_notifications/1 def destroy @invite_notification.destroy end private # Use callbacks to share common setup or constraints between actions. def set_invite_notification @invite_notification = InviteNotification.find(params[:id]) end # Only allow a trusted parameter "white list" through. def invite_notification_params params.require(:invite_notification).permit(:notified_by_id) end end