text
stringlengths
10
2.61M
module IControl::LocalLB ## # The ProfileDiameter interface enables you to manipulate a local load balancer's Diameter # profile. class ProfileDiameter < IControl::Base set_id_name "profile_names" class ProfileDiameterStatisticEntry < IControl::Base::Struct; end class ProfileDiameterStatistics < IControl::Base::Struct; end class ProfileDiameterStatisticEntrySequence < IControl::Base::Sequence ; end ## # Creates this Diameter profile. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def create super end ## # Deletes all Diameter profile. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def delete_all_profiles super end ## # Deletes this Diameter profile. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def delete_profile super end ## # Gets the statistics for all the Diameter profile. # @rspec_example # @return [ProfileDiameterStatistics] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def all_statistics super end ## # Gets the names of the default profile from which this profile will derive default # values for its attributes. # @rspec_example # @return [String] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def default_profile super end ## # Gets the realm to which a Diameter message is to be routed, overriding a destination # realm present in the message. See set_destination_realm for more information. # @rspec_example # @return [ProfileString] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def destination_realm super end ## # Gets a list of all Diameter profile. # @rspec_example # @return [String] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def list super end ## # Gets the states to indicate whether overwrite destination host is enabled. See set_overwrite_destination_host_state # for more information. # @rspec_example # @return [ProfileEnabledState] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def overwrite_destination_host_state super end ## # Gets the Diameter Attribute Value Pair (AVP) used to indicate the parent AVP when # the persist AVP is embedded in a grouped AVP. See set_persist_avp for more information # on the AVP specification. # @rspec_example # @return [ProfileString] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def parent_avp super end ## # Gets the the Diameter Attribute Value Pair (AVP) on which to persist for each of # the profile given. See set_persist_avp for more information on the AVP specification. # @rspec_example # @return [ProfileString] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def persist_avp super end ## # Gets the statistics for this Diameter profile. # @rspec_example # @return [ProfileDiameterStatistics] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def statistics super end ## # Gets the version information for this interface. # @rspec_example # @return [String] def version super end ## # Determines whether this profile are base/pre-configured profile, or user-defined # profile. # @rspec_example # @return [boolean] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def is_base_profile super end ## # Resets the statistics for this Diameter profile. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def reset_statistics super end ## # Sets the names of the default profile from which this profile will derive default # values for its attributes. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. # @param [Hash] opts # @option opts [String] :defaults The default profiles from which the specified profiles will get default values. def set_default_profile(opts) opts = check_params(opts,[:defaults]) super(opts) end ## # Sets the realm to which a Diameter message is to be routed, overriding a destination # realm present in the message. If a message does not have a destination realm, then # this setting has no effect. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. # @param [Hash] opts # @option opts [IControl::LocalLB::ProfileString] :realms The destination realms for the specified profiles. def set_destination_realm(opts) opts = check_params(opts,[:realms]) super(opts) end ## # Sets the states to indicate whether overwrite destination host is enabled. If it # is enabled, the system will overwrite the Destination-Host AVP (in a request) with # the pool member's address. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. # @param [Hash] opts # @option opts [IControl::LocalLB::ProfileEnabledState] :states The states to set. def set_overwrite_destination_host_state(opts) opts = check_params(opts,[:states]) super(opts) end ## # Sets the Diameter Attribute Value Pair (AVP) used to indicate the parent AVP when # the persist AVP is embedded in a grouped AVP. See set_persist_avp for more information # on the AVP specification. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. # @param [Hash] opts # @option opts [IControl::LocalLB::ProfileString] :avps The attribute value pair acting as parent for the persist AVP for the specified profiles. def set_parent_avp(opts) opts = check_params(opts,[:avps]) super(opts) end ## # Sets the Diameter Attribute Value Pair (AVP) on which to persist for each of the # profile given. The AVP specification can be a string or a numeric code (1-4294967295), # encoded as string. If the string is empty, or the code does not exist in the traffic # coming to the system, then persist is disabled (if the name is not recognized, this # method will produce an error). See RFC 3588, section 4.5, for valid base numeric # codes. Valid names are as follows, in any mix of upper and lower case: &amp;quot;auth-application-id", # &amp;quot;destination-host", &amp;quot;destination-realm", &amp;quot;origin-host", # &amp;quot;origin-realm", &amp;quot;session-id", &amp;quot;subscription-id", &amp;quot;subscription-id-data". # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. # @param [Hash] opts # @option opts [IControl::LocalLB::ProfileString] :avps The attribute value pair on which to persist for the specified profiles. def set_persist_avp(opts) opts = check_params(opts,[:avps]) super(opts) end ## # A struct that describes statistics for a particular Diameter profile. # @attr [String] profile_name The profile name. # @attr [IControl::Common::StatisticSequence] statistics The statistics for the profile. class ProfileDiameterStatisticEntry < IControl::Base::Struct icontrol_attribute :profile_name, String icontrol_attribute :statistics, IControl::Common::StatisticSequence end ## # A struct that describes profile statistics and timestamp. # @attr [IControl::LocalLB::ProfileDiameter::ProfileDiameterStatisticEntrySequence] statistics The statistics for a sequence of profiles. # @attr [IControl::Common::TimeStamp] time_stamp The time stamp at the time the statistics are gathered. class ProfileDiameterStatistics < IControl::Base::Struct icontrol_attribute :statistics, IControl::LocalLB::ProfileDiameter::ProfileDiameterStatisticEntrySequence icontrol_attribute :time_stamp, IControl::Common::TimeStamp end ## A sequence of ProfileDiameter statistics. class ProfileDiameterStatisticEntrySequence < IControl::Base::Sequence ; end end end
class PartnerProductsWidenPartnerKey < ActiveRecord::Migration def self.up change_table :partner_products do |t| t.change :partner_key, :string, :limit => 128 end end def self.down change_table :partner_products do |t| t.change :partner_key, :string, :limit => 16 end end end
# # Copyright 2009 Huygens Instituut for the History of the Netherlands, Den Haag, The Netherlands. # # This file is part of New Women Writers. # # New Women Writers is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # New Women Writers is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with New Women Writers. If not, see <http://www.gnu.org/licenses/>. # require 'cases/helper' require 'models/post' class EachTest < ActiveRecord::TestCase fixtures :posts def setup @posts = Post.all(:order => "id asc") @total = Post.count end def test_each_should_excecute_one_query_per_batch assert_queries(Post.count + 1) do Post.find_each(:batch_size => 1) do |post| assert_kind_of Post, post end end end def test_each_should_raise_if_the_order_is_set assert_raise(RuntimeError) do Post.find_each(:order => "title") { |post| post } end end def test_each_should_raise_if_the_limit_is_set assert_raise(RuntimeError) do Post.find_each(:limit => 1) { |post| post } end end def test_find_in_batches_should_return_batches assert_queries(Post.count + 1) do Post.find_in_batches(:batch_size => 1) do |batch| assert_kind_of Array, batch assert_kind_of Post, batch.first end end end def test_find_in_batches_should_start_from_the_start_option assert_queries(Post.count) do Post.find_in_batches(:batch_size => 1, :start => 2) do |batch| assert_kind_of Array, batch assert_kind_of Post, batch.first end end end def test_find_in_batches_shouldnt_excute_query_unless_needed post_count = Post.count assert_queries(2) do Post.find_in_batches(:batch_size => post_count) {|batch| assert_kind_of Array, batch } end assert_queries(1) do Post.find_in_batches(:batch_size => post_count + 1) {|batch| assert_kind_of Array, batch } end end end
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception before_action :configure_permitted_parameters, if: :devise_controller? rescue_from ActiveRecord::RecordNotFound, with: :render_404 rescue_from ActionController::RoutingError, with: :routing_error def routing_error respond_to do |format| format.html { render :partial => 'home/error_404', status: 404 } end end protected def configure_permitted_parameters added_attrs = [:first_name, :last_name, :email, :password, :password_confirmation,:admin, :remember_me] devise_parameter_sanitizer.permit :sign_up, keys: added_attrs devise_parameter_sanitizer.permit :account_update, keys: added_attrs end def render_404 respond_to do |format| format.html { redirect_to root_path, alert: 'Record Not Found' } end end end
class AddEnailIndexToKitchens < ActiveRecord::Migration def self.up add_index :kitchens, :email, :unique => true end def self.down remove_index :kitchens, :email end end
class AprofilesController < ApplicationController before_filter :authenticate_academic! def new @aprofile = Aprofile.new @aprofile.academic_id = current_academic.id @departments = Department.order(:title) end def create @aprofile = Aprofile.new(params[:aprofile]) @aprofile.academic_id = current_academic.id if @aprofile.save flash[:notice] = "You have created your profile successfully!" redirect_to root_path else flash[:notice] = "Profile not saved" render :action => 'new' end end def show @aprofile = Aprofile.find_by_academic_id(params[:id]) unless current_academic.id == @aprofile.academic_id flash[:notice] = "You don't have access to this page!" redirect_to contact_path return end respond_to do |format| format.html # show.html.erb format.json { render :json => @aprofile } end end def edit @aprofile = Aprofile.find_by_id(params[:id]) @departments = Department.order(:title) end def update @aprofile = Aprofile.find_by_academic_id(params[:id]) if @aprofile.update_attributes(params[:aprofile]) flash[:notice] = "Your profile was successfully updated!" redirect_to aprofile_path(@aprofile) else flash[:notice] = "Update was not saved." render :action => 'edit' end end end
require "./q7/menu" class Q7::Food < Q7::Menu attr_accessor :calorie def initialize(name:, price:, calorie:) super(name: name, price: price) @calorie = calorie end end
class CreateSports < ActiveRecord::Migration def change create_table :sports do |t| t.string :name, index: true, null: false t.references :user, index: true, foreign_key: true, null: false end end end
module Syouhai KACHI = 0 AIKO = 1 MAKE = 2 end #module-end
require "rails_helper" RSpec.feature "Admin Manage User", :type => :feature do before do @admin = create(:admin) sign_in(@admin) click_link 'User Management' expect(page).to have_content('Listing Users') end it "can create user" do click_link 'New User' fill_in 'user_fullname', with: 'New Fullname' fill_in 'user_username', with: 'new_username' fill_in 'user_email', with: 'new@gmail.com' fill_in 'user_password', with: 'password' fill_in 'user_password_confirmation', with: 'password' select 'Teacher', from: 'user_role' check 'user_activated' click_button 'Create User' expect(page).to have_content('User was successfully created.') end it "can edit user" do click_link 'Edit' expect(page).to have_content('Editing User') fill_in 'user_fullname', with: 'Updated Fullname' fill_in 'user_username', with: 'updated_username' click_button 'Update User' expect(page).to have_content('User was successfully updated.') expect(page).to have_content('Updated Fullname') end it "validates blank fullname" do click_link 'New User' fill_in 'user_fullname', with: '' fill_in 'user_username', with: 'new_username' fill_in 'user_email', with: 'new@gmail.com' fill_in 'user_password', with: 'password' fill_in 'user_password_confirmation', with: 'password' select 'Teacher', from: 'user_role' check 'user_activated' click_button 'Create User' expect(page).to have_content("Fullname can't be blank") end it "validates unique fullname" do click_link 'New User' fill_in 'user_fullname', with: @admin.fullname fill_in 'user_username', with: 'new_username' fill_in 'user_email', with: 'new@gmail.com' fill_in 'user_password', with: 'password' fill_in 'user_password_confirmation', with: 'password' select 'Teacher', from: 'user_role' check 'user_activated' click_button 'Create User' expect(page).to have_content("Fullname must be unique!") end it "validates blank username" do click_link 'New User' fill_in 'user_fullname', with: '' fill_in 'user_username', with: '' fill_in 'user_email', with: 'new@gmail.com' fill_in 'user_password', with: 'password' fill_in 'user_password_confirmation', with: 'password' select 'Teacher', from: 'user_role' check 'user_activated' click_button 'Create User' expect(page).to have_content("Username can't be blank") end it "validates unique username" do click_link 'New User' fill_in 'user_fullname', with: '' fill_in 'user_username', with: @admin.username fill_in 'user_email', with: 'new@gmail.com' fill_in 'user_password', with: 'password' fill_in 'user_password_confirmation', with: 'password' select 'Teacher', from: 'user_role' check 'user_activated' click_button 'Create User' expect(page).to have_content("Username must be unique!") end it "validates blank email" do click_link 'New User' fill_in 'user_fullname', with: 'Fullname' fill_in 'user_username', with: 'Username' fill_in 'user_email', with: '' fill_in 'user_password', with: 'password' fill_in 'user_password_confirmation', with: 'password' select 'Teacher', from: 'user_role' check 'user_activated' click_button 'Create User' expect(page).to have_content("Email can't be blank") end it "validates invalid format email" do click_link 'New User' fill_in 'user_fullname', with: 'Fullname' fill_in 'user_username', with: 'new_username' fill_in 'user_email', with: 'invalid-email.com' fill_in 'user_password', with: 'password' fill_in 'user_password_confirmation', with: 'password' select 'Teacher', from: 'user_role' check 'user_activated' click_button 'Create User' expect(page).to have_content("Email is invalid") end it "validates blank password" do click_link 'New User' fill_in 'user_fullname', with: 'Fullname' fill_in 'user_username', with: 'new_username' fill_in 'user_email', with: 'good@email.com' fill_in 'user_password', with: '' fill_in 'user_password_confirmation', with: 'password' select 'Teacher', from: 'user_role' check 'user_activated' click_button 'Create User' expect(page).to have_content("Password can't be blank") end it "validates not matched password & confirmation" do click_link 'New User' fill_in 'user_fullname', with: 'Fullname' fill_in 'user_username', with: 'new_username' fill_in 'user_email', with: 'good@email.com' fill_in 'user_password', with: 'password' fill_in 'user_password_confirmation', with: 'not matched' select 'Teacher', from: 'user_role' check 'user_activated' click_button 'Create User' expect(page).to have_content("Password confirmation doesn't match Password") end end
module DataSource class Middleman def initialize(resource) @resource = resource end def title @resource.data[:title] end # Episode paths look like this: # episodes/001-business-travel.html # # This method will parse out a 1 from the example path. def episode_number filename = @resource.path.split('/').last filename.split('-').first.to_i end def date @resource.data[:date] end def file @resource.data[:file] end def file_size @resource.data[:file_size] end def body @resource.render(layout: false) end def url @resource.url end end end
class RelatedTransaction < ActiveRecord::Base belongs_to :get_transaction, class_name: :transaction end
class ArticlesController < ApplicationController before_filter :load_article, :only => [:show, :edit, :destroy] before_filter :upcaser, :only => [:index] before_filter :filter_comments, :only => [:show] around_filter :flash_apology, :only => [:index] # around_filter :flash_apology, :only => [:show, :edit, :destroy] # GET /articles # GET /articles.json def index @articles = Article.all raise if @articles.blank? respond_to do |format| format.html # index.html.erb format.json { render json: @articles } end end # GET /articles/1 # GET /articles/1.json def show @article = Article.includes(:comments).find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @article } end end # GET /articles/new # GET /articles/new.json def new @article = Article.new respond_to do |format| format.html # new.html.erb format.json { render json: @article } end end # GET /articles/1/edit def edit end # POST /articles # POST /articles.json def create @article = Article.new(params[:article]) respond_to do |format| if @article.save format.html { redirect_to @article, notice: 'Article was successfully created.' } format.json { render json: @article, status: :created, location: @article } else format.html { render action: "new" } format.json { render json: @article.errors, status: :unprocessable_entity } end end end # PUT /articles/1 # PUT /articles/1.json def update respond_to do |format| if @article.update_attributes(params[:article]) format.html { redirect_to @article, notice: 'Article was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @article.errors, status: :unprocessable_entity } end end end # DELETE /articles/1 # DELETE /articles/1.json def destroy @article.destroy respond_to do |format| format.html { redirect_to articles_url } format.json { head :no_content } end end private def load_article @article = Article.find(params[:id]) end def upcaser @articles = Article.all @articles.each do |a| a.title.upcase! end end def filter_comments @comments = @article.comments.each do |c| c.body.gsub!('sad', 'happy') end end def blank_articles begin yield rescue render :text => "No Articles" end end def flash_apology begin yield rescue redirect_to new_article_path, notice: 'Sorry' end end end
require 'spec_helper' describe "Pages" do subject { page } describe "Home page" do it "should have the title 'MBlizz'" do visit root_path expect(page).to have_title("MBlizz") end describe "for signed in user" do let(:user) { FactoryGirl.create(:user) } before do FactoryGirl.create(:micropost, user: user, content: "Lorem ipsum") FactoryGirl.create(:micropost, user: user, content: "Dolor sit amet") sign_in user visit root_path end it "should render user feed" do user.feed.each do |item| expect(page).to have_selector("li##{item.id}", text: item.content) end end describe "follower/following count" do let(:other_user) { FactoryGirl.create(:user) } before do other_user.follow!(user) visit user_path(user) end it { should have_link('0 Following', href: following_user_path(user)) } it { should have_link('1 Followers', href: followers_user_path(user)) } end end end describe "Help" do it "should have the title 'Help'" do visit help_path expect(page).to have_title("Help") end end describe "About page" do it "should have the title 'About'" do visit about_path expect(page).to have_title("About") end end describe "Contact page" do it "should have the title 'Contact us'" do visit contact_path expect(page).to have_title("Contact Us") end end describe "Terms page" do it "should have the title 'Terms & Conditions'" do visit terms_path expect(page).to have_title("Terms & Conditions") end end describe "Privacy page" do it "should have the title 'Privacy Policy'" do visit privacy_path expect(page).to have_title("Privacy Policy") end end describe "Team page" do it "should have the title 'Team'" do visit team_path expect(page).to have_title("Team") end end end
require 'minitest/reporters' Minitest::Reporters.use! require 'minitest/autorun' class HelloTest < Minitest::Test def test_greeting assert_equal 'hello world!!', greeting end end def greeting 'hello world' end
require 'rails_helper' feature 'post new question', %Q{ As a user I want to post a question So that I can receive help from others } do # Acceptance Criteria # - I must provide a title that is at least 40 characters long # - I must provide a description that is at least 150 characters long # - I must be presented with errors if I fill out the form incorrectly scenario 'user views the details of a question' do visit '/' click_link('New question') fill_in('Title', with: 'Test question 1 has to be fill with more than 40 chars') description = 'a' * 151 fill_in('Description', with: description) click_button('Create Question') expect(page).to have_content('Test question 1 has to be fill with more than 40 chars') end scenario 'user post new question with empty title' do question = FactoryGirl.create(:question) visit '/' click_link('New question') fill_in('Title', with: '') click_button('Create Question') expect(page).to have_content('Title can\'t be blank') expect(page).to have_content('Title is too short (minimum is 40 characters)') end scenario 'user post new question with empty description' do question = FactoryGirl.create(:question) visit '/' click_link('New question') fill_in('Description', with: '') click_button('Create Question') expect(page).to have_content('Description can\'t be blank') expect(page).to have_content('Description is too short (minimum is 150 characters)') end end
require 'rubygems' require 'xmlparser' module OSMLib module Stream # Stream parser for OpenStreetMap XML files using Expat. class Parser::Expat < OSMLib::Stream::ParserBase # Create new StreamParser object. Only argument is a hash. # # call-seq: OSMLib::Stream::Parser.new(:filename => 'filename.osm') # OSMLib::Stream::Parser.new(:string => '...') # # The hash keys: # :filename => name of XML file # :string => XML string # :db => an OSMLib::Database object # :callbacks => an OSMLib::Stream::Callbacks object (or more likely from a # derived class) # if none was given a new OSM:Callbacks object is # created # # You can only use :filename or :string, not both. def initialize(options) super(options) @parser = XML::Parser.new if @filename.nil? @data = @string else @data = File.open(@filename) end end # Run the parser. Return value is the return value of the # OSMLib::Stream::Callbacks#result method. def parse @callbacks.on_start_document @parser.parse(@data) do |type, name, data| @position += @parser.byteCount @callbacks.on_start_element(name, data) if type == :START_ELEM @callbacks.on_end_element(name) if type == :END_ELEM end @callbacks.on_end_document @callbacks.result end end end end
class History < ApplicationRecord belongs_to :concrete_history, polymorphic: true belongs_to :card validates :card, presence: true validate :read_history_validates def read_history_validates if concrete_history.kind_of? ReadHistory if concrete_history.page_count >= card.book.page errors.add(:concrete_history, ' : read_history.page_count should be less than book.page.') end end end end
class Carousel < ApplicationRecord has_many :timeline_posts, dependent: :nullify has_many :timelines, through: :timeline_posts has_many :images, -> { order(:position) }, as: :container end
# == Schema Information # # Table name: languages # # id :integer not null, primary key # name :string(255) # links_count :integer # created_at :datetime # updated_at :datetime # class Language < ActiveRecord::Base has_many :tags, inverse_of: :language has_many :links, through: :tags, order: 'votes_count DESC' validates :name, presence: true, uniqueness: { case_sensitive: false } before_create :generate_slug def generate_slug self.slug = self.name.downcase.gsub(/[^\w\-]+/, "-") end def to_param slug end end
class Birthday @@filepath = nil def self.filepath=(path=nil) @@filepath = File.join(APP_ROOT, path) end #checks if the file we are looking exists in the correct directory def self.file_exists? if @@filepath && File.exists?(@@filepath) return true else return false end end #checks if the file is valid def self.file_usable? return false unless @@filepath return false unless File.exists?(@@filepath) return false unless File.readable?(@@filepath) return true end #if file doesnt exist it creates one def self.create_file File.open(@@filepath, 'w') unless file_exists? return file_usable? end #gets the array of that line in predefined order(1st name, last name, year, month, day) def import_line(line) line_array = line.split(' ') @primeiro_nome, @ultimo_nome, @ano, @mes, @dia = line_array return line_array end #creates the final array that will be worked with def self.get_birthdays birthdays = [] if file_usable? file = File.new(@@filepath, 'r') file.each_line do |line| birthdays << Birthday.new.import_line(line.chomp) end file.close end return birthdays end end
module UserTodoRules::Common module AddFunFacts def rule_triggerable?(user); Answer.count(:joins=>"JOIN questions on question_id = questions.id JOIN users on user_id=users.id", :conditions => ["user_id = ? AND questions.question_type='fun fact'", user.id]) == 0; end def rule_link_url(user); { :profile_mode => :my_home, :screen_name => user.screen_name, :controller => 'profile_home', :action => 'index', :anchor => 'fun_facts' }; end end module CheckYourStats def rule_triggerable?(user); user.stat.review_page_views.to_i > 10; end def rule_link_url(user); { :profile_mode => :my_home, :screen_name => user.screen_name, :controller => 'profile_stats', :action => 'index' }; end end module CompleteYourDrafts def rule_triggerable?(user); user.drafts.count > 0; end def rule_link_url(user); '/my_home#drafts'; end end module FindMoreFriends def rule_triggerable?(user); user.friendships.count(:conditions => 'created_at > DATE_SUB(CURDATE(), INTERVAL 30 DAY)') == 0; end def rule_link_url(user); { :profile_mode => :my_home, :screen_name => user.screen_name, :controller => 'profile_friends_and_fans', :action => 'index' }; end end module FindPeopleLikeYou def rule_triggerable?(user); user.stat.friends.to_i < 2; end def rule_link_url(user); { :profile_mode => :my_home, :screen_name => user.screen_name, :controller => 'profile_friends_and_fans', :action => 'index' }; end end module IntroduceYourselfToTheCommunitySkYou def rule_triggerable?(user); user.stat.post_count.to_i == 0; end def rule_link_url(user); { :controller => 'topics', :action => 'index', :forum_id => 'Welcome-Get-Started' }; end end module IntroduceYourselfToTheCommunity def rule_triggerable?(user); user.stat.post_count.to_i == 0; end def rule_link_url(user); { :controller => 'topics', :action => 'index', :forum_id => 'Welcome-Get-Started' }; end end module InviteAFriend def rule_triggerable?(user); UserInvitation.count(:conditions => ['user_id = ?', user.id]) == 0; end def rule_link_url(user); '/invite'; end end module JoinADiscussion def rule_triggerable?(user); user.stat.post_count.to_i > 0 && Post.count(:conditions => ['user_id = ? AND created_at > DATE_SUB(CURDATE(), INTERVAL 30 DAY)', user.id]) == 0; end def rule_link_url(user); '/discussion_boards'; end end module JoinADiscussionJustReg def rule_triggerable?(user); user.stat.post_count.to_i == 0; end def rule_link_url(user); '/discussion_boards'; end end module WriteAReview def rule_triggerable?(user); true; end def rule_link_url(user); '/write'; end end module ShareYourIdeas def rule_triggerable?(user); user.ideas.select{|i| i.idea_instance == IdeaInstance.find_by_cobrand_id(user.cobrand.id)}.size == 0; end def rule_link_url(user); "/#{IdeaInstance.find_by_cobrand_id(user.cobrand.id).short_name}"; end end module MessageAFriend def rule_triggerable?(user); user.messages_sent.count(:conditions => "created_at > DATE_SUB(CURDATE(), INTERVAL 30 DAY)") == 0; end def rule_link_url(user); {:profile_mode => :my_home, :screen_name => user.screen_name, :controller => "profile_friends_and_fans", :action => "index"}; end end module LeaveHelpfulVotes def rule_triggerable?(user); Helpful.count(:conditions => ['user_id = ?', user.id]) == 0; end def rule_link_url(user); '/recent_reviews'; end end module LeaveMoreHelpfulVotes def rule_triggerable?(user); Helpful.count(:conditions => ['user_id = ? AND updated_at > DATE_SUB(CURDATE(), INTERVAL 30 DAY)', user.id]) == 0; end def rule_link_url(user); '/recent_reviews'; end end module UpdateFunFacts def rule_triggerable?(user); Answer.count(:joins=>"JOIN questions on question_id = questions.id JOIN users on user_id=users.id", :conditions => ["user_id = ? AND questions.question_type='fun fact' AND answers.updated_at > DATE_SUB(CURDATE(), INTERVAL 60 DAY)", user.id]) == 0; end def rule_link_url(user); { :profile_mode => :my_home, :screen_name => user.screen_name, :controller => 'profile_home', :action => 'index', :anchor => 'fun_facts' }; end end module UpdateMotto def rule_triggerable?(user); Answer.count(:joins=>"JOIN questions on question_id = questions.id JOIN users on user_id=users.id", :conditions => ["user_id = ? AND questions.question_type='motto'", user.id]) == 0; end def rule_link_url(user); { :profile_mode => :my_home, :screen_name => user.screen_name, :controller => 'profile_home', :action => 'index' }; end end module UpdateYourEmailSettings def rule_triggerable?(user); user.notification_preferences.count(:conditions => 'updated_at > DATE_SUB(CURDATE(), INTERVAL 90 DAY)') == 0; end def rule_link_url(user); { :profile_mode => :my_home, :screen_name => user.screen_name, :controller => 'profile_email_settings', :action => 'index' }; end end module UpdateYourEmailSettingsAfterReg def rule_triggerable?(user); user.notification_preferences.count(:conditions => ['updated_at > DATE_ADD(?, INTERVAL 1 MINUTE)', user.created_at]) == 0; end def rule_link_url(user); { :profile_mode => :my_home, :screen_name => user.screen_name, :controller => 'profile_email_settings', :action => 'index' }; end end module UpdateYourInterests def rule_triggerable?(user); user.user_interests.count(:conditions => 'updated_at > DATE_SUB(CURDATE(), INTERVAL 90 DAY)') == 0; end def rule_link_url(user); { :profile_mode => :my_home, :screen_name => user.screen_name, :controller => 'profile_interests', :action => 'index' }; end end module UpdateYourProfilePhotos def rule_triggerable?(user); user.photos.gallery.size > 0 && user.photos.count(:conditions => 'sort_order > 0 && updated_at > DATE_SUB(CURDATE(), INTERVAL 60 DAY)') == 0; end def rule_link_url(user); { :profile_mode => :my_home, :screen_name => user.screen_name, :controller => 'profile_photos', :action => 'index' }; end end module UploadAProfilePhoto def rule_triggerable?(user); user.photos.primary.nil?; end def rule_link_url(user); { :profile_mode => :my_home, :screen_name => user.screen_name, :controller => 'profile_photos', :action => 'index' }; end end module UploadMoreProfilePhotos def rule_triggerable?(user); user.photos.primary && user.photos.gallery.size == 0; end def rule_link_url(user); { :profile_mode => :my_home, :screen_name => user.screen_name, :controller => 'profile_photos', :action => 'index' }; end end module WriteABlogPost def rule_triggerable?(user); user.scribbles.count(:conditions => 'created_at > DATE_SUB(CURDATE(), INTERVAL 30 DAY)') == 0; end def rule_link_url(user); { :profile_mode => :my_home, :screen_name => user.screen_name, :controller => 'profile_blog', :action => 'index' }; end end module WriteFirstReview def rule_triggerable?(user); user.stat.reviews_written.to_i == 0; end def rule_link_url(user); '/write'; end end module WriteMoreReviews def rule_triggerable?(user); user.stat.reviews_written.to_i > 0 && user.reviews.count(:conditions => "status = 'active' AND published_at > DATE_SUB(CURDATE(), INTERVAL 14 DAY) AND content != ''") == 0; end def rule_link_url(user); '/write'; end end module WriteAnotherIdea def rule_triggerable?(user); user.ideas.count > 0 && user.ideas.count(:conditions => "created_at > DATE_SUB(CURDATE(), INTERVAL 60 DAY)") == 0; end def rule_link_url(user); "/#{IdeaInstance.find_by_cobrand_id(user.cobrand.id).short_name}"; end end module WriteQuickReviews def rule_triggerable?(user); user.stat.reviews_written.to_i == 0; end def rule_link_url(user); { :controller => 'quick_review', :action => 'new' }; end end module WriteMoreQuickReviews def rule_triggerable?(user); user.stat.reviews_written.to_i > 0 && user.reviews.count(:conditions => "status = 'active' AND published_at > DATE_SUB(CURDATE(), INTERVAL 30 DAY) AND content = ''") == 0; end def rule_link_url(user); { :controller => 'quick_review', :action => 'new' }; end end module AddIAmTags def rule_triggerable?(user); user.tags_by_tag_sort_order(nil, nil, 1).blank?; end def rule_link_url(user); { :profile_mode => :my_home, :screen_name => user.screen_name, :controller => 'profile_manage_i_am', :action => 'index' }; end end module TakeAPoll def rule_triggerable?(user) # unfortunately we cannot track completion of this event since it is offsite return true end def rule_link_url(user); { :controller => 'content', :action => 'surveys' } end end end
class AddressComponent include Mongoid::Document attr_reader :long_name, :short_name, :types def initialize hashkeys @long_name = hashkeys[:long_name] @short_name = hashkeys[:short_name] @types = hashkeys[:types] end end
class CapsuleCRM::User < CapsuleCRM::Base attr_accessor :username attr_accessor :name attr_accessor :currency attr_accessor :timezone attr_accessor :logged_in attr_accessor :party_id define_attribute_methods [:username, :name, :currency, :timezone, :logged_in, :party_id] def self.get_path '/api/users' end private # -- Class methods -- # nodoc def self.init_many(response) data = response['users'].try(:[], 'user') CapsuleCRM::Collection.new(self, data) end # nodoc def self.init_one(response) data = response['user'] new(attributes_from_xml_hash(data)) end # nodoc def self.xml_map map = { 'username' => 'username', 'name' => 'name', 'currency' => 'currency', 'timezone' => 'timezone', 'loggedIn' => 'logged_in', 'partyId' => 'party_id', } super.merge map end end
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception before_action :configure_permitted_parameters, if: :devise_controller? rescue_from CanCan::AccessDenied do |exception| flash[:error] = "Access denied." redirect_to root_url end def after_sign_in_path_for(resource) user = User.find(resource.id) # select_campaign_choice(user) # campaign = User.find(resource.id).campaigns.first # if campaign && campaign.private? # campaign_stores_path(campaign) # else # campaign_path(campaign) # end # @current_campaigns = Supporter.where(user_id: user.id) # if @current_campaigns.size == 1 # campaign = User.find(user.id).campaigns.first # if campaign && campaign.private? # campaign_stores_path(campaign) # else # campaign_path(campaign) # end # else # possible_campaigns_path(current_campaigns: @current_campaigns) and return # end end def after_sign_up_path_for(resource) if params[:redirect_to].present? store_location_for(resource, params[:redirect_to]) # elsif request.referer == new_session_url # super else stored_location_for(resource) || request.referer || root_path end end protected def configure_permitted_parameters devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:name, :email, :password, :image, :image_id, :remove_image, :campaign_code, :is_patient) } devise_parameter_sanitizer.for(:account_update) { |u| u.permit(:name, :email, :current_password, :password, :image, :image_id, :remove_image, :is_patient, :managed_account, :managed_name, :managed_email, :preferred_name, :zip_code, :gender, :symptoms, :diagnosis, :treatment_plan, :treatment_schedule, :item_needed_by, :normal_size, :plus_size, :petite_size, :other_notes, :dob, :favorite_brand) } end end
class AddSmColumnsToSmData < ActiveRecord::Migration def change add_column :sm_data, :movie_title, :string add_column :sm_data, :fb_page_name, :string add_column :sm_data, :fb_handle, :string add_column :sm_data, :twitter_handle, :string add_column :sm_data, :twitter_hashtag, :string add_column :sm_data, :twitter_page_name, :string add_column :sm_data, :instagram_id, :string add_column :sm_data, :instagram_handle, :string add_column :sm_data, :instagram_hashtag, :string add_column :sm_data, :klout_id, :string add_column :sm_data, :release_date, :datetime end end
class Admin::DashboardController < ApplicationController before_filter :authenticate_admin_user! layout "admin" def index if params[:id] @user=User.find(params[:id]) @user.update_attribute("role_id", params[:role]); end @unauthorized_users = User.where("role_id is NULL") @recent_login_users = User.order("current_sign_in_at desc").limit(5) @roles = Role.all respond_to do |format| format.html format.js end end end
class Question < ActiveRecord::Base validates :title, null: false, length: {minimum: 1} validates :comment, null: false, length: {maximum: 200, minimum: 1} has_many :answer, dependent: :destroy end
require 'ostruct' module RSpecSystem # This class represents a result from a helper command class Result < OpenStruct # Returns the value of a member. def [](name) @table[name.to_sym] end end end
module Wunderlist class Client BASE_URL = "https://a.wunderlist.com/api/v1" attr_reader :client_id, :access_token def initialize(client_id, access_token) @client_id = client_id @access_token = access_token end def get(url, params = {}) make_request(:get, url, params) end def post(url, payload = {}) make_request(:post, url, payload) end def patch(url, payload = {}) make_request(:patch, url, payload) end def delete(url, payload = {}) make_request(:delete, url, payload) end def make_request(method, url, payload = {}, headers = {}) url = "#{BASE_URL}/#{url}" headers = default_headers.merge(headers) response = RestClient::Request.execute( method: method, url: url, payload: payload.to_json, headers: headers ) response.empty? ? true : JSON.parse(response) rescue RestClient::Exception => e raise Wunderlist::Exception.from_response(e.http_code, e.http_body) end def default_headers { "X-Access-Token" => access_token, "X-Client-ID" => client_id, "Content-Type" => "application/json" } end def root get("root") end def lists ResourceProxy.new(self, false, List) end def users ResourceProxy.new(self, false, User) end def webhooks ResourceProxy.new(self, false, Webhook) end def tasks ResourceProxy.new(self, false, Task) end def subtasks ResourceProxy.new(self, false, Subtask) end def notes ResourceProxy.new(self, false, Note) end def comments ResourceProxy.new(self, false, Comment) end end end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'kilomeasure/version' Gem::Specification.new do |spec| spec.name = 'kilomeasure' spec.version = Kilomeasure::VERSION spec.authors = ['Wegonauts'] spec.email = ['developers@wegowise.com'] spec.description = 'Formulas for calculating potential building energy ' \ 'efficiency.' spec.summary = 'Collects numerous formulas that can be applied to ' \ 'building characteristics to calculate potential ' \ 'energy and cost savings.' spec.homepage = 'http://wegowise.com' spec.files = `git ls-files`.split($RS) spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ['lib'] spec.add_dependency 'dentaku', '~> 2.0.4', '>= 2.0' spec.add_dependency 'memoizer', '~> 1.0.1', '>= 1.0' spec.add_dependency 'activesupport', '~> 4.2.0', '>= 4.2' spec.add_dependency 'fattr', '~> 2.2', '>= 2.2.2' spec.add_development_dependency 'bundler' spec.add_development_dependency 'rake', '~> 10.0', '>= 10.0' spec.add_development_dependency 'rspec', '~> 3.3.0', '>= 3.3' spec.add_development_dependency 'pry', '~> 0.10', '>= 0.10' spec.add_development_dependency 'pry-byebug', '~> 3.0', '>= 3.2' spec.add_development_dependency 'pry-stack_explorer', '~> 0.4', '>= 0.4.9' spec.add_development_dependency 'overcommit', '~> 0.26', '>= 0.26' spec.add_development_dependency 'json-schema', '~> 2.5.1' end
class LikesController < ApplicationController # before_actionに「:authenticate_user」を追加してください before_action :authenticate_user # createアクションを追加してください def create @like = Like.new(user_id: @current_user.id, topic_id: params[:topic_id]) @like.save redirect_to("/topics/#{params[:topic_id]}") end def destroy @like = Like.find_by(user_id: @current_user.id, topic_id: params[:topic_id]) @like.destroy redirect_to("/topics/#{params[:topic_id]}") end end
require File.dirname(__FILE__) + '/../test_helper' require 'visitors_controller' # Re-raise errors caught by the controller. class VisitorsController; def rescue_action(e) raise e end; end class VisitorsControllerTest < ActionController::TestCase # Be sure to include AuthenticatedTestHelper in test/test_helper.rb instead # Then, you can remove it from this and the units test. include AuthenticatedTestHelper fixtures :visitors def test_should_allow_signup assert_difference 'Visitor.count' do create_visitor assert_response :redirect end end def test_should_require_login_on_signup assert_no_difference 'Visitor.count' do create_visitor(:login => nil) assert assigns(:visitor).errors.on(:login) assert_response :success end end def test_should_require_password_on_signup assert_no_difference 'Visitor.count' do create_visitor(:password => nil) assert assigns(:visitor).errors.on(:password) assert_response :success end end def test_should_require_password_confirmation_on_signup assert_no_difference 'Visitor.count' do create_visitor(:password_confirmation => nil) assert assigns(:visitor).errors.on(:password_confirmation) assert_response :success end end def test_should_require_email_on_signup assert_no_difference 'Visitor.count' do create_visitor(:email => nil) assert assigns(:visitor).errors.on(:email) assert_response :success end end protected def create_visitor(options = {}) post :create, :visitor => { :login => 'quire', :email => 'quire@example.com', :password => 'quire69', :password_confirmation => 'quire69' }.merge(options) end end
class CreatePropertyListings < ActiveRecord::Migration def change create_table :property_listings do |t| t.integer :bhk t.string :address t.string :property_type t.integer :buildup_area t.integer :bathrooms t.string :furnish_type t.integer :rent t.integer :security_deposit t.belongs_to :poster, index: true t.timestamps end end end
module ApplicationHelper # Returns the full title on a per-page basis. def full_title(page_title) base_title = "OneTeam" if page_title.empty? base_title else "#{base_title} | #{page_title}" end end def current_employee=(employee) @current_employee = employee end def current_employee @current_employee ||= Employee.find_by_remember_token(cookies[:remember_token]) end def current_employee?(employee) employee == current_employee end def nav_link(link_text, link_path) class_name = current_page?(link_path) ? 'active' : '' content_tag(:li, :class => class_name) do link_to link_text, link_path end end end
class ApplicationController < ActionController::Base before_action :authenticate_user! def current_company @current_company ||= current_user.company end end
Help::Engine.routes.draw do root to: "help_wanteds#index" scope 'admin' do resources :help_offereds resources :help_wanteds end scope 'api' do scope '1' do resources :help_offereds, controller: 'api/v1/help_offereds' resources :help_wanteds, controller: 'api/v1/help_wanteds' end end end
require 'rails_helper' feature "user sees new notifications" do before(:each) do user = FactoryBot.create(:user) @notification_1 = user.notifications.create(message: "hello there!") @notification_2 = user.notifications.create(message: "goodbye!") sign_in user visit root_path end scenario "the 'notifications' link is bold" do expect(page).to have_bold_notifications_link end scenario "the notifications are in descending order" do click_on "notifications" user_sees_content_order_descending(@notification_1.message, @notification_2.message) end scenario "once viewed, the 'notifications' link is no longer bold" do click_on "notifications" visit root_path expect(page).not_to have_bold_notifications_link end scenario "once viewed, the notifications disappear" do click_on "notifications" visit root_path click_on "notifications" expect(notifications_on_page.count).to eq(0) end scenario "once viewed, 'no new notifications' is displayed" do click_on "notifications" visit root_path click_on "notifications" expect(page).to have_content("no new notifications") end end
# coding: utf-8 require 'date' $:.unshift File.dirname(__FILE__) require 'jyear' # # 日付関係 # class GovDate # # 西暦⇒和暦変換 # #date :: 西暦年月日 # #返り値:: 和暦年月日 def to_jdate(date) date.to_time.strftime("%K年%m月%d日") end # # 和暦⇒西暦変換 # #jdate :: 和暦年月日 # #返り値:: 西暦年月日 def to_date(jdate) Date.parse(jdate).to_s end end
module Sources class TheHackerNews extend CD::RssParser def self.parse get_feed('https://feeds.feedburner.com/TheHackersNews') do |xml| parse_feed(xml) do |item| { title: item.at('title').text, description: CGI.escape_html(item.at('description').text.strip), link: item.at('link').text, comments: item.at('link').text, updated_at: updated_at(item), link_to_comments: item.at('link').text, link_host: 'thehackernews.com' } end end end private def self.updated_at(doc_item) unless doc_item.at('pubDate').nil? DateTime.parse(doc_item.at('pubDate').text).new_offset(0) end end end end
require 'test_helper' class SproutsControllerTest < ActionDispatch::IntegrationTest setup do @sprout = sprouts(:one) end test "should get index" do get sprouts_url assert_response :success end test "should get new" do get new_sprout_url assert_response :success end test "should create sprout" do assert_difference('Sprout.count') do post sprouts_url, params: { sprout: { department: @sprout.department, employee: @sprout.employee, store: @sprout.store } } end assert_redirected_to sprout_url(Sprout.last) end test "should show sprout" do get sprout_url(@sprout) assert_response :success end test "should get edit" do get edit_sprout_url(@sprout) assert_response :success end test "should update sprout" do patch sprout_url(@sprout), params: { sprout: { department: @sprout.department, employee: @sprout.employee, store: @sprout.store } } assert_redirected_to sprout_url(@sprout) end test "should destroy sprout" do assert_difference('Sprout.count', -1) do delete sprout_url(@sprout) end assert_redirected_to sprouts_url end end
class Puppy def fetch(toy) puts "I brought back the #{toy}!" toy end def speak(num) counter = 0 while counter < num puts "woof" counter += 1 end end def roll_over puts "*Rolls over*" end def dog_years(human_yrs) human_yrs * 7 end def pee_itself puts "*Wets self*" end def initialize puts "Initializin new puppy instance..." end end spot = Puppy.new spot.fetch("ball") spot.speak(4) spot.roll_over p spot.dog_years(12) spot.pee_itself class Kitten def scratch puts "Ouch! He scratched me." end def sleep puts "Oh look, he's sleeping." end end counter = 0 cat_array = [] while counter < 50 name = counter cat_array << name = Kitten.new counter = counter + 1 end p cat_array cat_array.each do |x| x.scratch x.sleep end
class Libraries::DownloadSoftwaresController < ApplicationController before_filter :authenticate_user!, :only => [:index, :new, :create, :edit, :update ] protect_from_forgery with: :null_session, :only => [:destroy, :delete] def index @soft = DownloadSoftware.where("type_of_cost_center LIKE '"+CostCenter.find(get_company_cost_center('cost_center')).speciality.to_s+"'") render layout: false end def show @soft = DownloadSoftware.find(params[:id]) render layout: false end def new @soft = DownloadSoftware.new render layout: false end def create flash[:error] = nil soft = DownloadSoftware.new(soft_parameters) if soft.save flash[:notice] = "Se ha creado correctamente." redirect_to :action => :index else soft.errors.messages.each do |attribute, error| puts flash[:error].to_s + error.to_s + " " end @soft = soft render :new, layout: false end end def edit @soft = DownloadSoftware.find(params[:id]) @action = 'edit' render layout: false end def update soft = DownloadSoftware.find(params[:id]) if soft.update_attributes(soft_parameters) flash[:notice] = "Se ha actualizado correctamente los datos." redirect_to :action => :index, company_id: params[:company_id] else soft.errors.messages.each do |attribute, error| flash[:error] = attribute " " + flash[:error].to_s + error.to_s + " " end # Load new() @soft = soft render :edit, layout: false end end def destroy soft = DownloadSoftware.destroy(params[:id]) flash[:notice] = "Se ha eliminado correctamente." render :json => soft end private def soft_parameters params.require(:download_software).permit(:name, :description, :file,:type_of_cost_center) end end
class Round < ActiveRecord::Base belongs_to :competition has_many :matches end
# Fact: has_infiniband # # Purpose: Determine if the system's hardware supports InfiniBand. # # Resolution: # Returns true or false based on output from `lspci`. # # Caveats: # Currently only tested with Mellanox and Qlogic cards installed in a system. # require 'facter/util/infiniband' Facter.add(:has_infiniband) do confine kernel: 'Linux' setcode do ib_device_count = Facter::Util::Infiniband.count_ib_devices ib_device_count > 0 end end
# frozen_string_literal: true require_relative 'balance' class Account def transactions if ledger.empty? puts 'No transactions yet' else ledger.each do |transaction| puts "Amount: #{transaction.first}, Date: #{transaction[1]}, Type: #{transaction.last}" end end end def current_balance balance.show_balance end def pay_in(amount) transaction_payin(amount) transaction_verification(amount, true) end def pay_out(amount) transaction_payout(amount) transaction_verification(amount, false) end private def transaction_verification(amount, type) if ledger.last.first == amount && amount > 0.01 balance_verification(amount, type) else puts 'Error: transaction not recorded' end end def balance_verification(amount, type) if type if balance.add_and_verify(amount) puts "You have now #{balance.show_balance} pounds in your account" else puts "Transaction unsuccessful, current balance: #{balance.show_balance} pounds" ledger.last << 'deposit - operation cancelled' end elsif balance.deduct_and_verify(amount) puts "You have now #{balance.show_balance} pounds in your account" else puts "Transaction unsuccessful, current balance: #{balance.show_balance} pounds" ledger.last << 'withdrawal - operation cancelled' end end def transaction_payin(amount) ledger << [amount, Time.now, :deposit] operation_cancellation(amount) end def transaction_payout(amount) ledger << [amount, Time.now, :withdrawal] operation_cancellation(amount) end def operation_cancellation(amount) ledger.last << 'activity reported to bank - operation cancelled' unless amount > 0.01 && amount.is_a?(Numeric) end protected attr_reader :ledger, :balance def initialize @balance = Balance.new @ledger = [] end end
require 'httparty' require 'json' class Skyscanner BASE_URL_SKY_ROUTES = 'http://partners.api.skyscanner.net/apiservices/browseroutes/v1.0/' BASE_URL_SKY_QUOTES = 'http://partners.api.skyscanner.net/apiservices/browsequotes/v1.0/' BASE_URL_SKY_LOC = 'http://partners.api.skyscanner.net/apiservices/autosuggest/v1.0/' MARKET = "US" CURRENCY = "USD" LOCALE = "en-US" DESTINATION = "anywhere" attr_accessor :quotes def initialize(data) @quotes = data['Quotes'] end def self.find_quotes(origin, departure_date, return_time) data = HTTParty.get(BASE_URL_SKY_QUOTES + MARKET + '/' + CURRENCY + '/' + LOCALE + '/' + origin + '/' + DESTINATION + '/' + departure_date + '/' + return_time + '?apiKey=' + ENV["SKYSCANNER_KEY"], headers: { 'Content-Type' => 'application/json' }) .parsed_response return self.new(data) end def self.sky48_codes(skyscanner_object) codes = skyscanner_object.quotes.map do |one_dest| one_dest["OutboundLeg"]["DestinationId"] end return codes end def self.clean(array, skyscanner_object) final = [] skyscanner_object.quotes.each do |one_dest| if array.include? one_dest["OutboundLeg"]["DestinationId"] final.push one_dest end end skyscanner_object.quotes = final return skyscanner_object end def self.clean_again(skyscanner_quotes) skyscanner_quotes.each do |qoute| repeated = skyscanner_quotes.find_all { |twin| twin["OutboundLeg"]["DestinationId"] == qoute["OutboundLeg"]["DestinationId"] } if repeated.length > 1 if repeated[0]['MinPrice'] > repeated[1]['MinPrice'] skyscanner_quotes.delete(repeated[0]) else skyscanner_quotes.delete(repeated[1]) end end end return skyscanner_quotes end def self.add_sum_prices(skyscanner1, skyscanner2) hash = {} skyscanner1.quotes.each do |destination| hash[destination["OutboundLeg"]["DestinationId"]] = destination['MinPrice'] end skyscanner2.quotes.each do |destination| hash[destination["OutboundLeg"]["DestinationId"]] += destination['MinPrice'] end skyscanner2.quotes.each do |destination| destination['SumPrices'] = hash[destination["OutboundLeg"]["DestinationId"]] end skyscanner1.quotes.each do |destination| destination['SumPrices'] = hash[destination["OutboundLeg"]["DestinationId"]] end skyscanner2.quotes = skyscanner2.quotes.sort_by { |destination| destination['SumPrices'] } skyscanner1.quotes = skyscanner1.quotes.sort_by { |destination| destination['SumPrices'] } final_array = [skyscanner1, skyscanner2] return final_array end def self.find_commun(one, two) array_one = self.sky48_codes(one) array_two = self.sky48_codes(two) array = array_one & array_two one = self.clean(array, one) two = self.clean(array, two) if one.quotes.length != two.quotes.length one.quotes = self.clean_again(one.quotes) two.quotes = self.clean_again(two.quotes) end final_array = self.add_sum_prices(one, two) return final_array end def self.matching_destinations (origin_one, origin_two, departure_date, return_date) origin_one = self.find_quotes(origin_one, departure_date, return_date) origin_two = self.find_quotes(origin_two, departure_date, return_date) return self.find_commun(origin_one, origin_two) end def self.findlocation(location_id) data = HTTParty.get( BASE_URL_SKY_LOC + MARKET + '/' + CURRENCY + '/' + LOCALE + '/?id=' + location_id.to_s + '-sky&apiKey=' + ENV["SKYSCANNER_KEY"], headers: { 'Content-Type' => 'application/json' }) .parsed_response return data end def self.get_session_key(origin, desti, departure_date, return_time) session = HTTParty.post( 'http://partners.api.skyscanner.net/apiservices/pricing/v1.0', body: { "apiKey" => ENV["SKYSCANNER_KEY"], "locale" => LOCALE, "country" => "US", "currency" => CURRENCY, "originplace" => "96322-sky48", "destinationplace" => "81665-sky48", "Outbounddate" => departure_date, "Inbounddate" => return_time, "adults" => 1 }, headers: { 'Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json' }) return session.headers['location'] end def self.findflights(origin_one, destination, departure_date, return_time) url = self.get_session_key(origin_one, destination, departure_date, return_time) data = HTTParty.get(url + "?apiKey=" + ENV["SKYSCANNER_KEY"]).parsed_response return self.new(data) end def self.destination_name(id) data = HTTParty.get("http://partners.api.skyscanner.net/apiservices/autosuggest/v1.0/" + MARKET + '/' + CURRENCY + '/' + LOCALE + '/?id=' + id.to_s + '-sky48&apiKey=' + ENV["SKYSCANNER_KEY"]) return data end end
require 'compiler_helper' module Alf class Compiler describe Default, "quota" do subject{ compiler.call(expr) } let(:summarization){ Summarization[{ max: Aggregator.max{ qty } }] } let(:ordering){ Ordering.new([[:b, :asc]]) } shared_examples_for "the expected Quota::Cesure" do it_should_behave_like "a traceable compiled" it 'has a Quota::Cesure cog' do expect(subject).to be_kind_of(Engine::Quota::Cesure) end it 'has the correct parameters' do expect(subject.by).to eq(AttrList[:a]) expect(subject.summarization).to be(summarization) end end context 'when not sorted' do let(:expr){ quota(an_operand(leaf), [:a], ordering, summarization) } it_should_behave_like "the expected Quota::Cesure" it 'has a Sort as sub-cog' do expect(subject.operand).to be_kind_of(Engine::Sort) expect(subject.operand.ordering).to eq(Ordering.new([[:a, :asc], [:b, :asc]])) end it 'has the leaf has sub-sub cog' do expect(subject.operand.operand).to be(leaf) end end context 'when already sorted' do let(:expr){ quota(sort(an_operand(leaf), subordering), [:a], ordering, summarization) } context 'in a compatible way' do let(:subordering){ Ordering.new([[:a, :asc], [:b, :asc]]) } it_should_behave_like "the expected Quota::Cesure" it_should_behave_like "a compiled reusing a sub Sort" end context 'in an incompatible way' do let(:subordering){ Ordering.new([[:a, :desc], [:b, :asc]]) } it_should_behave_like "the expected Quota::Cesure" it 'has a Sort as sub-cog' do expect(subject.operand).to be_kind_of(Engine::Sort) expect(subject.operand.ordering).to eq(Ordering.new([[:a, :asc], [:b, :asc]])) end it 'has a Sort as sub-sub-cog' do expect(subject.operand.operand).to be_kind_of(Engine::Sort) expect(subject.operand.operand.ordering).to be(subordering) end it 'has the leaf has sub-sub-sub cog' do expect(subject.operand.operand.operand).to be(leaf) end end end end end end
class SpaceStatusValidationValidator < ActiveModel::Validator def validate(record) items = [record.equipment_info, record.basic_info, record.description, record.space_image, record.plan] unless items.all? {|item| item.present? } record.errors[:status] << "未入力の情報があります" end end end
# coding: utf-8 feature 'ゲストとして、Twitterでログインしたい' do def mock_hash { "provider" => "twitter", "uid" => 1234567, "info" => { "nickname" => 'test_user_twitter', "image" => '...test.png' } } end background do OmniAuth.config.test_mode = true OmniAuth.config.mock_auth[:twitter] = mock_hash end context "登録してない場合" do background do User.delete_all end scenario 'ログインリンクでログイン出来る' do visit root_path page.should have_content "Twitterでログイン" click_link "Twitterでログイン" page.should have_content "test_user_twitter" end end context "登録した場合" do background do User.delete_all User.create_with_omniauth mock_hash end scenario 'ログインリンクでログイン出来る' do visit root_path page.should have_content "Twitterでログイン" click_link "Twitterでログイン" page.should have_content "test_user_twitter" end end end
class Task < ApplicationRecord validates :title, presence: true validates :done, inclusion: { in: [true, false] } belongs_to :tag, optional: true end
#!/usr/bin/env ruby require 'pry' require 'fileutils' require 'open-uri' require 'colorize' include FileUtils cmd = ARGV[0] project_name = ARGV[1] def make_project(project_name) # make app repo mkdir(project_name) # and do all the work there... cd(project_name) do # assets folders = %w( public public/images public/stylesheets views db controllers helpers config models spec ) makedirs(folders) File.open('db/seeds.rb', 'w+') do |f| f.write <<SEEDS require 'sequel' DB = Sequel.connect("postgres://localhost/#{project_name}_development") SEEDS end touch 'db/schema.sql' File.open('helpers/application_helper.rb', 'w+') do |f| f.write <<APPLICATION_HELPER module ApplicationHelper def link_to(title, path) '<a href="' + path + '">' + title + '</a>' end end APPLICATION_HELPER end # .rspec File.open('.rspec', 'w+') do |f| f.write <<RSPEC --color --format documentation --require spec_helper RSPEC end # spec_helper.rb File.open('spec/spec_helper.rb', 'w+') do |f| f.write <<SPEC_HELPER ENV['RACK_ENV'] = 'test' require 'rspec' require 'capybara/rspec' # this may need to change... require './app' Capybara.app = App RSpec.configure do |config| config.include Capybara::DSL end SPEC_HELPER end # styles # FileUtils.touch touch("public/stylesheets/style.css") File.open('public/stylesheets/normalize.css', 'w+') do |f| normalize_url = 'https://raw.githubusercontent.com/necolas/normalize.css/master/normalize.css' f.write(open(normalize_url).read) end # views File.open('views/layout.erb', 'w+') do |f| f.write <<HTML <!doctype html> <html> <head> <meta charset="utf-8"> <title>#{project_name}</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="/stylesheets/normalize.css" rel="stylesheet" type="text/css" media="all"> <link href="/stylesheets/style.css" rel="stylesheet" type="text/css" media="all"> </head> <body> <h1>Hello from Layout.erb!</h1> <%= yield %> </body> </html> HTML end # Index.erb File.open('views/index.erb', 'w+') do |f| f.write <<INDEX <h1>Hello from Index!</h1> INDEX end # Gemfile File.open('Gemfile', 'w+') do |f| f.write <<GEMFILE source 'https://rubygems.org' # May have to update if/when I update my Ruby ruby '2.1.2' # Gems used in every environment gem 'sinatra', '1.4.5', require: 'sinatra/base' gem 'redis', '3.1.0' gem 'httparty', '0.13.1' gem 'sequel', '~> 4.14.0' gem 'pg', '~> 0.17.1' # only used in development locally group :development, :test do gem 'pry', '0.10.1' gem 'sinatra-contrib' end # gems specific just in the production environment group :production do end group :test do gem 'rspec', '~> 3.0.0' gem 'capybara', '~> 2.4.1' end GEMFILE end # default app! File.open('controllers/application_controller.rb', 'w+') do |f| f.write <<APPLICATION_CONTROLLER class ApplicationController < Sinatra::Base ######################## # Configuration ######################## set :app_file, File.expand_path(File.dirname(__FILE__), '../') helpers ApplicationHelper # allow put/delete forms in browsers that don't support it. enable :method_override # store data between HTTP requests in a cookie enable :sessions # session_secret will change with every start of the application # if we want to run shotgun, which creates new application instances # we must manually set session_secret set :session_secret, 'super secret' configure :test, :development do require 'sinatra/reloader' register Sinatra::Reloader end end APPLICATION_CONTROLLER end # config.ru File.open('config.ru', 'w+') do |f| f.write <<CONFIG require 'rubygems' require 'bundler' Bundler.require(:default, ENV['RACK_ENV'] || 'development') require './config/boot' map('/') { run RootController } CONFIG end File.open('config/boot.rb', 'w+') do |f| f.write <<BOOT_FILE DB = Sequel.connect("postgres://localhost:5432/#{project_name}_development") Dir['./helpers/*.rb'].each { |helper| require helper } Dir['./models/*.rb'].each { |model| require model } require './controllers/application_controller' Dir['./controllers/*.rb'].each { |controller| require controller } BOOT_FILE end # app.rb File.open('controllers/root_controller.rb', 'w+') do |f| f.write <<APP class RootController < ApplicationController get('/') do render(:erb, :index) end end APP end system('bundle install') puts('>> OK!'.white) puts(">> Created #{project_name}!".green) puts('>> use `bundle exec rackup -p 3000` from inside the folder to run it!') end end if cmd == 'new' make_project(project_name) elsif cmd == 'server' system('bundle exec rackup -p 3000') elsif cmd == 'console' require 'rubygems' require 'bundler' Bundler.require(:default, ENV['RACK_ENV'] || 'development') require './config/boot' puts 'Starting console...' # how to get working based on blogpost # ARGV.delete('console') # Pry::CLI.parse_options Pry.start else puts "don't know that command" end
#!/usr/bin/env ruby1.9 -ryaml # encoding: UTF-8 # Lets YAML know that valid UTF-8 strings are not binary data. # This will get you a double-quoted string output, meaning all # non-ASCII characters will be escaped in \xDD format. # The good news is that double-quoted strings, when imported back # by ruby 1.9's YAML::load, will be read in the default encoding # (which should then be UTF-8), not as BINARY/ASCII-8BIT. # For fully unescaped UTF-8 output, checkout the ya2yaml gem. String.def_around :is_binary_data?, :utf8_dump_double_quoted do !(encoding == Encoding.find("UTF-8") && valid_encoding?) && is_binary_data_without_utf8_dump_double_quoted? end # ruby 1.8's YAML dumper tends to tag strings as !binary willy-nilly. # This fix attempts to convert all strings back to the default # encoding (which generally should be UTF-8, unless you're importing # YAML data that was dumped from strings with a different encoding). # When loading YAML, for every string that comes in with an encoding # that is not the default, we try to force and validate it. # Valid strings are returned with the new default encoding. Invalid # ones are reset back to their original. YAML::DefaultResolver.def_around :node_import, :try_default_encoding do |node| node_import_without_try_default_encoding(node).tap do |s| next unless %w( encoding force_encoding valid_encoding? ).all? { |m| s.respond_to?(m) } next unless s.encoding != __ENCODING__ original_encoding = s.encoding s.force_encoding(__ENCODING__) s.force_encoding(original_encoding) unless s.valid_encoding? end end
module Sdc3 class Image < Struct.new(:url, :available, :dimensions, :x, :y) include Sdc3::StructHelper def initialize(tag) super return unless tag self.available = Sdc3.first_attr(tag, 'available') self.x = Sdc3.first_attr(tag, 'width') self.y = Sdc3.first_attr(tag, 'height') self.url = Sdc3.first_text(tag, 'sourceURL') members_to_b :available members_to_i :x, :y # derived properties self.dimensions = "#{self.x}x#{self.y}" end def self.parse_many(parent, child_name=nil) child_name ||= 'image' Sdc3::parse_many parent, child_name, Image end end # of class Image end # of module Sdc
class Signup < ActiveRecord::Base include PayPal::SDK::REST attr_protected def self.sept_fees {:participant => 375, :student => 30, :clergy => 175, :guest => 175, :dinner => 190} end def self.fees if Time.now.to_i < 1473048000 {:participant => 325, :student => 30, :clergy => 150, :guest => 150, :dinner => 190} else sept_fees end end def fee(type) fees[type] end def self.participant_fee fees[:participant] end def self.student_fee fees[:student] end def self.dinner_fee fees[:dinner] end def self.clergy_fee fees[:clergy] end def self.guest_fee fees[:guest] end def total fees = Signup.fees total = fees[self.attendee_type.to_sym] if self.accompanied total = total + fees[:guest] if self.dinner total = total + 2*fees[:dinner] end else if self.dinner total = total + fees[:dinner] end end return total end def self.client "AYds8Bs42CXtrThrSOgGtxPca5DcljQWfsvMrbCGl8TE-sRCJ-LgsOz3YUqsvOO3qubWTBp-JNUY3vdg" end def self.secret "EKhIg5qPVxx51xfnOQIRXj6CStp-sxB0aNc3MAlNaD76L600UM5KykbL5164itFbhebNvg0Uc_5iuqPr" end def name first_name + " " + last_name end def self.payment(cc, signup) payment = Payment.new({ :intent => "sale", :payer => { :payment_method =>"credit_card", :funding_instruments => [{ :credit_card => cc }] }, :transactions => [{ :amount => { :total => signup.total, :currency => "USD" }, :description => "Ticket for #{signup.name}" }] }) if payment.create return true, payment.id else return false, payment.error end end def attendee_type_v {:student => "student", :clergy => "Clergy/Religious/Academic/Teacher", :participant => "participant"}[attendee_type.to_sym] end end
require 'rails_helper' describe Tagging, type: :model do before :each do @post = FactoryGirl.create(:post) @tagging = @post.taggings.take end subject { @tagging } it { is_expected.to belong_to(:tag) } it { is_expected.to belong_to(:post) } describe "Class Methods" do context "#post_count(tag_name)" do before :each do create_list(:ruby_post, 4) end it "when exist the posts" do expect(Tagging.post_count("ruby")).to eq 4 end it "when absence of posts" do expect(Tagging.post_count("js")).to eq 0 end end end end
class ParticipantResponse < ActiveRecord::Base belongs_to :participant belongs_to :participant_survey has_and_belongs_to_many :multiple_choices, :class_name => 'SurveyQuestionChoice' belongs_to :single_choice, :class_name => 'SurveyQuestionChoice' belongs_to :question, :class_name => 'SurveyQuestion' validates_presence_of :participant, :question validates_uniqueness_of :question_id, :scope => :participant_id validates_numericality_of :numeric_response, :allow_blank => true, :only_integer => true validate :question_required after_create :set_next_question, :check_and_set_complete after_destroy :set_next_question, :check_and_set_complete def choices (multiple_choices + [single_choice]).compact end def question_required if question.required? case question.qtype when 'Select One', 'Yes/No', 'True/False' then errors.add :single_choice_id, 'You must respond to this question' if single_choice_id.blank? when 'Select Multiple' then errors.add :multiple_choice_ids, 'You must respond to this question' if multiple_choice_ids.blank? when 'Text' then errors.add :text_response, 'You must respond to this question' if text_response.blank? when 'Date', 'Date/Time', 'Time' then errors.add :datetime_response, 'You must respond to this question' if datetime_response.blank? when 'Numeric' then errors.add :numeric_response, 'You must respond to this question' if numeric_response.blank? end end end def previous_response participant.responses. joins('join survey_questions on survey_questions.id = participant_responses.question_id'). where('survey_questions.position < ? and survey_questions.survey_id = ?', question.position, question.survey_id). order('survey_questions.position desc'). first end def destroy_following_responses! participant.responses. joins('join survey_questions on survey_questions.id = participant_responses.question_id'). where('survey_questions.position > ? and survey_questions.survey_id = ?', question.position, question.survey_id). destroy_all end protected def set_next_question if participant_survey next_question = nil questions_unanswered = question.survey.questions.where('position > ?', question.position) questions_unanswered.each do |question| if question.parent_choice if earlier_response = participant.responses.find_by_question_id(question.parent_choice.question.id) if earlier_response.choices.collect(&:id).include? question.parent_choice.id next_question = question break end end else next_question = question break end end participant_survey.update_attribute :next_question, next_question end end def check_and_set_complete if participant_survey if participant_survey.next_question.nil? or all_required_questions_answered? participant_survey.update_attribute :complete, true end end end def all_required_questions_answered? true if question.survey.questions.where('position > ? and required = true', question.position).count == 0 end end
class Country < ActiveRecord::Base #Countryインスタンスの人口が1000人以上だったら # manyを999人以下だったらfewを返す命令(method) def many_or_few if self .population > 1000 'many' else 'few' end end end
class Driver attr_reader :name @@all = [] def initialize(name) @name = name @@all << self end def passengers # passengers = [] # Ride.all.each do |ride| # passengers << ride.passenger if ride.driver == self # end # passengers self.rides.map{|ride|ride.passenger} #map is pulling the .passenger value out. end def rides Ride.all.select {|ride|ride.driver == self} end def self.all @@all end def driver_distance self.rides.reduce(0) do |sum, ride| sum + ride.distance end end def self.mileage_cap(distance) # self.all.select{|driver|driver if driver.driver_distance > distance} self.all.select{|driver| driver.driver_distance > distance} end end
class User < ActiveRecord::Base has_many :articles has_secure_password attr_accessor :remember_token VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i validates :score_in, presence: true, numericality: { greater_than_or_equal_to: 0 } validates :score_out, presence: true, numericality: { greater_than_or_equal_to: 0 } validates :name, presence: true, length: { maximum: 50 } validates :email, presence: true, length: { maximum: 100 }, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false } #allow_blank true is ok since has_secure_password validates on object creation #only other time password touched is changing passwords (ok), and changing emails #where changing emails interprets password as < 6 length since we don't .require it #allow_blank works around this issue validates :password, length: { minimum: 6 }, allow_blank: true def voting_power self.score_in/self.score_out end def remember self.remember_token = User.new_token update_attribute(:remember_digest, User.digest(self.remember_token)) end def forget update_attribute(:remember_digest, nil) end def transition_to_no_power(prev_power) no_power = false if (self.voting_power == 0 && prev_power != 0) no_power = true end return no_power end def authenticated?(remember_token) return false if remember_digest.nil? BCrypt::Password.new(remember_digest).is_password?(remember_token) end class << self def digest(string) cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : BCrypt::Engine.cost BCrypt::Password.create(string, cost: cost) end def new_token SecureRandom.urlsafe_base64 end end end
module UploadImageRetainLowQuality class S3 CONFIG_FILE = ".upload_image_retain_low_qualityrc" def initialize file = if FileTest.file?(CONFIG_FILE) CONFIG_FILE else [Dir.home, CONFIG_FILE].join("/") end raise "no aws config file" unless FileTest.file?(file) @s3 = ::AWS::S3.new(YAML.load_file(file)) end def buckets @s3.buckets end def bucket=(bucket) @bucket = bucket end def directories directories = @bucket.as_tree({prefix: current_path}).children.select(&:branch?).collect(&:prefix) directories.map{|dir| dir.split("/").last} end def current_path @prefix end def cd(prefix) @prefix = [@prefix, prefix].compact.join("/") end def upload_file(file, to_path, opts = {}) raise "set bucket at first" unless @bucket to_path = [to_path, file].compact.join("/") acl = opts[:acl] || :private #p puts "#{file} to #{to_path}" obj = @bucket.objects[to_path] || @bucket.create(to_path) obj.write(File.open(file), { :acl => acl }) end # Class Methods class << self def generate_config if FileTest.file?(CONFIG_FILE) Console.print_red "#{CONFIG_FILE} is already exists" else config = <<"CONFIG" access_key_id: 'YOUR ACCESS KEY' secret_access_key: 'SECRET ACCESS KEY' CONFIG f = File.new(CONFIG_FILE, "w") f << config f.close Console.print_green "#{CONFIG_FILE} was created" end end end # Class Methods End end end
module RobotMaker def RobotMaker.create(x=0, y=0, direction="EAST", allowed_to_move=true) Class.new { define_method(:allowed_to_move?) { allowed_to_move } define_method(:x) { x } define_method(:y) { y } define_method(:direction) { direction } define_method(:enter_arena) { false } }.new end end
require 'net/http' require 'guard' require 'guard/guard' require 'guard/watcher' module Guard # The Jasmine guard that gets notifications about the following # Guard events: `start`, `stop`, `reload`, `run_all` and `run_on_change`. # class Jasmine < Guard autoload :Inspector, 'guard/jasmine/inspector' autoload :Runner, 'guard/jasmine/runner' autoload :Server, 'guard/jasmine/server' autoload :Util, 'guard/jasmine/util' extend Util attr_accessor :last_run_failed, :last_failed_paths, :run_all_options DEFAULT_OPTIONS = { :server => :auto, :server_env => ENV['RAILS_ENV'] || 'development', :server_timeout => 15, :port => 8888, :jasmine_url => 'http://localhost:8888/jasmine', :timeout => 10000, :spec_dir => 'spec/javascripts', :notification => true, :hide_success => false, :all_on_start => true, :keep_failed => true, :clean => true, :all_after_pass => true, :max_error_notify => 3, :specdoc => :failure, :console => :failure, :errors => :failure, :focus => true } # Initialize Guard::Jasmine. # # @param [Array<Guard::Watcher>] watchers the watchers in the Guard block # @param [Hash] options the options for the Guard # @option options [String] :server the server to use, either :auto, :none, :webrick, :mongrel, :thin, :jasmine_gem, or a custom rake task # @option options [String] :server_env the server environment to use, for example :development, :test # @option options [Integer] :server_timeout the number of seconds to wait for the Jasmine spec server # @option options [String] :port the port for the Jasmine test server # @option options [String] :jasmine_url the url of the Jasmine test runner # @option options [String] :phantomjs_bin the location of the PhantomJS binary # @option options [Integer] :timeout the maximum time in milliseconds to wait for the spec runner to finish # @option options [String] :spec_dir the directory with the Jasmine specs # @option options [Boolean] :notification show notifications # @option options [Boolean] :hide_success hide success message notification # @option options [Integer] :max_error_notify maximum error notifications to show # @option options [Boolean] :all_on_start run all suites on start # @option options [Boolean] :keep_failed keep failed suites and add them to the next run again # @option options [Boolean] :clean clean the specs according to rails naming conventions # @option options [Boolean] :all_after_pass run all suites after a suite has passed again after failing # @option options [Symbol] :specdoc options for the specdoc output, either :always, :never or :failure # @option options [Symbol] :console options for the console.log output, either :always, :never or :failure # @option options [Symbol] :errors options for the errors output, either :always, :never or :failure # @option options [Symbol] :focus options for focus on failures in the specdoc # @option options [Hash] :run_all options overwrite options when run all specs # def initialize(watchers = [], options = { }) options[:jasmine_url] = "http://localhost:#{ options[:port] }/jasmine" if options[:port] && !options[:jasmine_url] options = DEFAULT_OPTIONS.merge(options) options[:specdoc] = :failure if ![:always, :never, :failure].include? options[:specdoc] options[:server] ||= :auto options[:phantomjs_bin] = Jasmine.which('phantomjs') unless options[:phantomjs_bin] self.run_all_options = options.delete(:run_all) || {} super(watchers, options) self.last_run_failed = false self.last_failed_paths = [] end # Gets called once when Guard starts. # # @raise [:task_has_failed] when run_on_change has failed # def start if Jasmine.phantomjs_bin_valid?(options[:phantomjs_bin]) Server.start(options[:server], options[:port], options[:server_env], options[:spec_dir]) unless options[:server] == :none if Jasmine.runner_available?(options) run_all if options[:all_on_start] end else throw :task_has_failed end end # Gets called once when Guard stops. # # @raise [:task_has_failed] when stop has failed # def stop Server.stop unless options[:server] == :none end # Gets called when the Guard should reload itself. # # @raise [:task_has_failed] when run_on_change has failed # def reload self.last_run_failed = false self.last_failed_paths = [] end # Gets called when all specs should be run. # # @raise [:task_has_failed] when run_on_change has failed # def run_all passed, failed_specs = Runner.run([options[:spec_dir]], options.merge(self.run_all_options)) self.last_failed_paths = failed_specs self.last_run_failed = !passed throw :task_has_failed unless passed end # Gets called when watched paths and files have changes. # # @param [Array<String>] paths the changed paths and files # @raise [:task_has_failed] when run_on_change has failed # def run_on_changes(paths) specs = options[:keep_failed] ? paths + self.last_failed_paths : paths specs = Inspector.clean(specs, options) if options[:clean] return false if specs.empty? passed, failed_specs = Runner.run(specs, options) if passed self.last_failed_paths = self.last_failed_paths - paths run_all if self.last_run_failed && options[:all_after_pass] else self.last_failed_paths = self.last_failed_paths + failed_specs end self.last_run_failed = !passed throw :task_has_failed unless passed end end end
require 'rails_helper' feature 'Cloning sampled structures', :omniauth, :js do let!(:user) { create(:user) } let!(:audit) { create(:audit, user: user) } let!(:common_area_type) do create(:audit_strc_type, name: 'Common Area', parent_structure_type: audit.audit_structure.audit_strc_type) end let!(:sample_group) do create(:sample_group, name: 'Hallways', parent_structure: audit.audit_structure, audit_strc_type: common_area_type) end let!(:existing_structure) do create(:audit_structure, name: 'My existing structure', audit_strc_type: common_area_type, sample_group: sample_group) end before do signin_as(user) visit audits_path click_audit audit.name click_structure_row 'Hallways' end scenario 'once, with a single name' do click_structure_row 'My existing structure', action: 'Clone' fill_in 'Number of copies', with: 1 fill_in 'Name Pattern', with: 'My new structure' click_button 'Create' expect(page).to have_structure_row 'My new structure' end scenario 'with a letter wildcard' do click_structure_row 'My existing structure', action: 'Clone' fill_in 'Number of copies', with: 2 fill_in 'Name Pattern', with: 'My new structure ?' click_button 'Create' expect(page).to have_structure_row 'My new structure A' expect(page).to have_structure_row 'My new structure B' end scenario 'with a numerical wildcard' do click_structure_row 'My existing structure', action: 'Clone' fill_in 'Number of copies', with: 2 fill_in 'Name Pattern', with: 'My new structure #' click_button 'Create' expect(page).to have_structure_row 'My new structure 1' expect(page).to have_structure_row 'My new structure 2' end scenario 'is unavailable when an audit is locked' do audit.update(locked_by: user.id) visit current_path expect(page).to_not have_structure_action 'Clone' end end
class DeleteArtistIdFromGenres < ActiveRecord::Migration[5.2] def change remove_column :genres, :artist_id end end
require 'oystercard' describe Oystercard do let(:station){ double :station } it 'should have a balance of 0' do expect(subject.balance).to eq(0) end it "should top up oystercard" do expect {subject.top_up(5)}.to change { subject.balance }.by(5) end it "should throw error if =>£90" do max_limit = Oystercard::MAX_LIMIT subject.top_up(max_limit) expect{ subject.top_up 1 }.to raise_error "Reached max limit of £90" end it 'should deduct spending' do max_limit = Oystercard::MAX_LIMIT subject.top_up(max_limit) expect(subject.deduct 10).to eq(80) end it 'is in journey' do expect(subject).not_to be_in_journey end it 'can touch in' do subject.top_up(1) subject.touch_in(station) expect(subject).to be_in_journey end it 'can touch out' do subject.top_up(1) subject.touch_in(station) subject.touch_out(station) expect(subject).not_to be_in_journey end it 'will require £1 to touch in' do expect{subject.touch_in(station)}.to raise_error "Insufficient funds to touch in" end it 'will deduct fare' do min_fare = Oystercard::MIN_FARE subject.top_up(1) subject.touch_in(station) expect {subject.touch_out(station)}.to change{subject.balance}.by(-min_fare) end it 'saves entry station' do subject.top_up(1) subject.touch_in(station) expect(subject.entry_station).to eq station end it 'stores exit station' do subject.top_up(1) subject.touch_in(station) expect(subject.touch_out(station)).to eq station end it 'has an empty list of journeys by default' do expect(subject.journeys).to be_empty end let(:journey){ {entry_station: entry_station, exit_station: exit_station} } let(:entry_station) { double :station } let(:exit_station) { double :station } it 'stores a journey' do subject.top_up(1) subject.touch_in(entry_station) subject.touch_out(exit_station) expect(subject.journeys).to include journey end end
class RemoveColumnsFromSongs < ActiveRecord::Migration[6.0] def change remove_column :songs, :spotify_url, :string remove_column :songs, :qq_url, :string remove_column :songs, :net_ease_url, :string end end
require 'r_package_extractor' class PackageRefinementJob @queue = :r_packages # Method to update Package ad Version with details from Description file of a package # It also creates an Author for the version, is it doesnt already have one # TODO: Separate into smaller methods # def self.perform(version_id) version = Version.find(version_id) package = version.r_package package_extractor = RPackageExtractor.new(version.package_name, version.number) package_extractor.set_package_info version.update(package_extractor.version_hash) package.update(package_extractor.package_hash) version.set_author package_extractor.author_hash version.add_maintainer package_extractor.maintainer_hash end end
# How does count treat the block's return value? How can we find out? ['ant', 'bat', 'caterpillar'].count do |str| str.length < 4 end # Per Ruby documentation for count with a block: issues a warning, ignores the block, and returns the count of elements eql? to obj. # => 2 # LS Explanation: # If a block is given, counts the number of elements for which the block returns a true value. # From this we can conclude that count only counts an element if the block's return value evaluates to true. # This means that count considers the truthiness of the block's return value.
class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable devise :omniauthable, omniauth_providers: [:facebook] has_many :reviews has_many :favorites def self.find_for_facebook_oauth(auth) user_params = auth.slice(:provider, :uid) user_params.merge! auth.info.slice(:email, :first_name, :last_name) user_params[:facebook_picture_url] = auth.info.image user_params[:token] = auth.credentials.token user_params[:token_expiry] = Time.at(auth.credentials.expires_at) user_params = user_params.to_h user = User.find_by(provider: auth.provider, uid: auth.uid) user ||= User.find_by(email: auth.info.email) # User did a regular sign up in the past. if user user.update(user_params) else user = User.new(user_params) user.password = Devise.friendly_token[0,20] # Fake password for validation user.save end return user end def interactions codes_cis = self.favorites.where(now: true).collect { |favorite| favorite.code_cis} codes_cis_couples = codes_cis.combination(2).to_a unless codes_cis.size < 2 interactions = [] unless codes_cis_couples.nil? codes_cis_couples.each do |couple| interaction = DrugService.interactions(couple.first, couple.last) interactions << interaction unless interaction.empty? end end interactions end end
module Autogrid module Formatter class << self # TODO: make changeable! def boolean(view, value, options = {}) if options == :image return value ? view.image_tag('ui_check.png') : view.image_tag('ui_status_inactive.png') end if options == :inverse or options == :reverse value = !value end return value ? 'Yes' : 'No' end def currency(view, value, options = {}) view.number_to_currency value end end end end
class Validator class << self def validate(schema_path, json_body) JSON::Validator.validate!( Rails.root.join("app/models/schemas/#{schema_path}.json").to_s, json_body ) rescue JSON::Schema::ValidationError => e message = e.message.gsub /did not match the regex.*/, "was invalid." raise ValidationError.new(message) end end end
# encoding: utf-8 namespace :sections do desc "Import regions" task :import_regions => :environment do regions_json = JSON.parse(File.read(Rails.root.to_s + "/db/seeds/regions.json")) regions_json.each do |region_hash| id = region_hash.delete("id") region = Region.new(region_hash) region.id = id region.save end end desc "Import state region_ids" task :import_region_ids => :environment do states_json = JSON.parse(File.read(Rails.root.to_s + "/db/seeds/states.json")) states_json.each do |state_hash| state = State.find_by_name(state_hash["name"]) if state state.region_id = state_hash["region_id"] state.save else puts "The state #{state_hash["name"]} was not found" end end end desc "Import districts" task :import_districts => :environment do states_json = JSON.parse(File.read(Rails.root.to_s + "/db/seeds/states.json")) districts_json = JSON.parse(File.read(Rails.root.to_s + "/db/seeds/districts.json")) districts_json.each do |district_hash| state_id = district_hash.delete("state_id") district_id = district_hash.delete("id") head = district_hash.delete("head") district = District.new(district_hash) state_hash = states_json.find {|h| h["id"] == state_id} state = State.find_by_name(state_hash["name"]) district.state_id = state.id district.id = district_id district.save end end desc "Import sections" task :import_sections => :environment do sections_json = JSON.parse(File.read(Rails.root.to_s + "/db/seeds/sections.json")) sections_json.each do |section_hash| section_id = section_hash.delete("id") section = Section.new(section_hash) section.id = section_id section.save end end desc "Import everything" task :import => :environment do Rake::Task["sections:import_regions"].invoke Rake::Task["sections:import_region_ids"].invoke Rake::Task["sections:import_districts"].invoke Rake::Task["sections:import_sections"].invoke end end
module AdminArea module CardRecommendations # Mark as 'expired' all recommendations which: # # a) were recommended to the user more than [setting] days ago # b) have not been interacted with by the user (clicked, declined, or # applied for) # c) are not already expired # # Users won't see expired recs anymore on their /cards page. # # This operation will be run from a script that runs daily in production. class ExpireOld < Trailblazer::Operation self['expire_after_no_of_days'] = 180 step :expire_old_recs! private def expire_old_recs!(opts) Card.recommended.unclicked.unapplied.unexpired.undeclined.where( "recommended_at < '#{opts['expire_after_no_of_days'].days.ago.utc.to_s(:db)}'", ).update_all(expired_at: Time.zone.now) end end end end
class UsersController < ApplicationController include FinduserHelper before_action(:find_user, {only: [:edit, :index ,:update, :show, :destroy] }) def new @user = User.new render(:new) end def create @user = User.new(user_params) if @user.save session["user_id"]=@user.id redirect_to user_path(@user) else render(:new) end end def index if current_user.superuser == true @users = User.all render(:index) else redirect_to user_path(session["user_id"]) end end def edit end def update @user.update(user_params) redirect_to user_path(@user.id) end def destroy @user.destroy redirect_to(:back) end def show @tasks = Task.where(user_id: params[:id]) @tasks = @tasks.order(:due_date) @connections_connector = Connection.where("user_id = ? AND c_type = ?", params[:id], "Connector") @connections_mentor = Connection.where("user_id = ? AND c_type = ?", params[:id], "Mentor") @connections_peer = Connection.where("user_id = ? AND c_type = ?", params[:id], "Peer") @task = Task.new @connection = Connection.new if current_user.superuser || current_user.id == params[:id].to_i render(:show) else redirect_to user_path(current_user.id) end end def authenticate unless logged_in? redirect_to login_path end end def authorize unless current_user == @user redirect_to login_path end end private def user_params params.require(:user).permit(:name, :title, :email, :password, :password_confirmation) end end
#! /usr/bin/env ruby # TODO # # 3. The ability to control output "select rhs.field lhs.field" # 4. More efficient disk storage systems (+my/sql/ite) # 5. Threading on disk reads # 6. ETAs and better output # # # Large CSV merging app. uses an index construction method to merge CSVs in excess of memory size require 'csv' LOW_MEMORY = false # Keep memory usage to an absolute minimum (not recommended unless you have almost no RAM) STRICT_GC = true # Garbage collect after large operations (recommended) OUTPUT_DIVISOR = 512 # print the line every n lines. Should be a largeish and fast-to-divide number, ie a power of 2 module CacheMethods class Cache # Add an item to the cache # # Key will be the CSV minimal key # offset will be the file offset, int. def []=(key, offset) puts "STUB: []= in CacheMethods::Cache" end # Retrieve a file offset using a key # # key will be the CSV minimal key def [](key) puts "STUB: [] in CacheMethods::Cache" end # Signal that we no longer wish to make any # changes # # This allows the cache to optimise itself, or # switch to read only mode. def finalise end # Signal that we no longer wish to use the store # This allows things to remove their disk stuff # and/or clean up RAM def cleanup end end # Holds everything in an in-memory hash for speed class MemoryCache < Cache def initialize @cache = {} end def []=(key, offset) @cache[key] = offset end def [](key) @cache[key] end end # Holds everything in PStore. # VERY SLOW, but works. class DiskCache < Cache def initialize(filename="/tmp/csvmerge.tmp", transaction_size=10000) require 'pstore' @cache = PStore.new(filename, false) @read_only = false @pending = {} @transaction_size = transaction_size.to_i end def []=(key, offset) raise "Cannot store!" if @read_only # Write into the memory cache-cache @pending[key] = offset # If we hit the transaction count, write write_to_disk if @pending.size >= @transaction_size end def [](key) @cache.transaction(true){|cache| return cache[key] } end def finalise write_to_disk @read_only = true end def cleanup File.rm(@cache.path) end private def write_to_disk @cache.transaction(false){|cache| @pending.each{|k, v| cache[k] = v } } end end end # Provides a wrapper around CSV # that will perform various checks and descriptive statistical ops. class KeyValueCSV attr_reader :keys, :filename def initialize(filename, keys) @filename = filename # Load keys @keys = (keys.empty?) ? fields : keys # Check all the keys are there @keys.each{|k| raise "Key is not in fields list" if not fields.include?(k) } end def say(arg) puts "[#{File.basename(@filename)}] #{arg}" end def minimal_keys compute_minimal_keys if not @minimal_keys @minimal_keys end # Total size of the key def key_size compute_minimal_keys if not @key_length @key_length end # Retrieve a key from a line def get_minimal_key(line) compute_minimal_keys if not @minimal_keys str = "" minimal_keys.each{|k, size| str += line.field(k).to_s[0..size] } return str end def fields build_fields if not @fields @fields end def count build_count if not @count @count end def to_s return "#{@filename}" end def cache=(cache) raise "Cannot set cache when seeking" if @handle @cache = cache build_index end def seek_retrieval(&block) File.open(@filename, 'r') do |handle| @handle = handle yield @handle = nil end end def []=(k, v) raise "No Cache!" if not @cache @cache[k] = v end def [](k) raise "Cannot retrieve from cache if not seeking" if not @handle raise "No Cache" if not @cache # Seek to the location in the cache and return a line if seek_to = @cache[k] then @handle.seek(seek_to) return CSV.parse_line(@handle.readline, :encoding => 'utf-8', :headers => fields).to_hash else return nil end end private # Construct an index. Should not need to be # overidden def build_index say "Building index..." # Get size in bytes, so we know when we've hit the end. file_size = File.size(@filename) CSV.open(@filename, :encoding => 'utf-8', :headers => true) do |csvin| # Get byte offset line_start = csvin.tell # Then read line count = 0 while((line_start = csvin.tell) < file_size) do # Load the line line = csvin.shift() # Load the key up to the key size only key = get_minimal_key(line) # Save the file offset # TODO: ensure random access of the cache is possible $stderr.puts "WARNING: Key at byte #{line_start} of #{@filename} collides with key at byte #{@cache[key]}." if @cache[key] @cache[key] = line_start print "\rLine: #{count+=1} " end end print "\n" say "Finished building index" end def compute_minimal_keys @minimal_keys = {} say "Calculating minimum index size (0/2)..." # Set up per-key prefix table and max length measure prefix_tables = {} max_lengths = {} @keys.each{ |k| max_lengths[k] = 0 # length of the field prefix_tables[k] = [] # position-usage measure } # Enable garbage collector stress mode, to keep memory clean GC.stress = true if LOW_MEMORY count = 0 CSV.foreach(@filename, :encoding => 'utf-8', :headers => true) do |csvin| prefix_tables.each{ |key, prefix| val = csvin.field(key).to_s # For each position, for each char, keep a count. pos = 0 val.each_char{ |c| prefix[pos] = {} if not prefix[pos] prefix[pos][c] = 0 if not prefix[pos][c] prefix[pos][c] += 1 pos += 1 } # Check on the maximum length for this field max_lengths[key] = pos if max_lengths[key] < pos } # count records print "\rLine: #{count} " if (count+=1) % OUTPUT_DIVISOR == 0 end print "\rLine: #{count} " # ensure we print the last number to avoid confusion print "\n" # OPTIMISATION: # completes file size count if not done already @count = count if not @count say "Prefix tables complete (1/2)" # And turn it off again GC.stress = false if LOW_MEMORY GC.start if STRICT_GC say "Computing minimum size (2/2)..." # For each key, compute the minimal size from the prefix table count = 0 prefix_tables.each{|key, prefix| print "\rField: #{count+=1}/#{prefix_tables.size}" # From the hash of prefixes, determine the shortest possible prefix key_size = 0 prefix.each{|chars| key_size += 1 max = 1 # puts "prefix for field #{key}, filename #{@filename}: position #{key_size} sees #{prefix[key_size-1].size} #{chars.size} different chars." chars.each{|k, v| max = v if v > max } break if max == 1 # Each char is at this point used only once } throw "No key values for field #{key} in #{@filename}" if key_size == 0 # If the final character position has only seen one character # then this field is NOT unique # non_unique_fields << key if prefix[key_size-1].length == 1 # FIXME # if prefix[key_size-1].length == 1 then # end # FIXME # puts "\nWARNING: field '#{key}' in #{@filename} is uninformative, with an entropy of 0." if key_size == 0 # Write the minimal key size for this key @minimal_keys[key] = key_size } print "\n" say "Minimum index size established." # Lastly, compute total key length @key_length = minimal_keys.values.inject(0, :+) end def build_count say "Counting items..." count = 0 # Enable garbage collector stress mode, to keep memory clean GC.stress = true if LOW_MEMORY count = CSV.read(@filename, :encoding => 'utf-8', :headers => true).length # CSV.foreach(@filename, {:headers => true}) do |csvin| # count += 1 # end # And turn it off again GC.stress = false if LOW_MEMORY GC.start if STRICT_GC say "Count complete." @count = count end def build_fields say "Building field list..." csv = CSV.open(@filename, 'r', :encoding => 'utf-8', :headers => true ) # Shift once to get past the header, if it exists csv.shift() row = csv.shift() # Then list headers and close list = row.headers csv.close say "Field list complete." # Ensure they're strings @fields = list.map!{|x| x.to_s } end end module MergePolicy class Merge def initialize(lhs, rhs) @lhs, @rhs = lhs, rhs end # Output fields as they will be, i.e. for the header. # Prefix them with rhs. if they would otherwise be dupes. def fields @lhs.fields + (@rhs.fields - @rhs.keys).map{|f| @lhs.fields.include?(f) ? "rhs.#{f}" : f } end def to_s "Merge" end def accept_line?(lhs_line, rhs_line) puts "WARNING: No merge policy." return false end # Merge a single line def merge_line(lhs_line, rhs_line) line = [] # Add all left hand side items @lhs.fields.each{ |f| line << lhs_line[f] } # and only non-key fields from the RHS (@rhs.fields - @rhs.keys).each{|f| line << rhs_line[f] } return line end end class LeftMerge < Merge def to_s "Left Merge" end def accept_line?(lhs_line, rhs_line) # Left outer joins returns ALL from LHS, even if RHS is empty true end end class InnerMerge < Merge def to_s "Inner Merge" end def accept_line?(lhs_line, rhs_line) # Inner join returns rows ONLY if both have data (not lhs_line.empty?) and (not rhs_line.empty?) end end # TODO # # An outer join will output even if # one half of the key is missing, # but match up what it can # class OuterMerge < Merge # def to_s # "Outer Merge" # end # # # Accept ALL, in fact, generate some. # # currently impossible using this algorithm # def accept_line?(lhs_line, rhs_line) # end # end # TODO: # # A cross join is the cartesian product of # both files. # # Currently not possible with the framework as it is # class CrossMerge < Merge # def to_s # "Custom Merge" # end # def accept_line?(lhs_line, rhs_line) # end # end end def process_commandline_args # Parse command line args if ARGV.length < 5 then $stderr.puts "USAGE: #{__FILE__} LHS RHS OUT MERGE_POLICY CACHE lkey1 lkey2 lkey3... -- rkey1 rkey2 rkey3..." exit(1) end # Load the basics lhs = ARGV[0] rhs = ARGV[1] out = ARGV[2] policy = ARGV[3] cache = ARGV[4] lhs_keys = [] rhs_keys = [] if not %w{LeftMerge InnerMerge}.include?(policy) then $stderr.puts "No such merge policy: '#{policy}'" exit(1) end if not File.exist?(lhs) $stderr.puts "File does not exist: #{lhs}" exit(1) end if not File.exist?(rhs) $stderr.puts "File does not exist: #{rhs}" exit(1) end if File.exist?(out) $stderr.puts "WARNING: Output file exists." end if not %w{MemoryCache DiskCache} then $stderr.puts "No such cache: '#{cache}'" exit(1) end # Load keys into the rhs, lhs key lists arr = lhs_keys ARGV[5..-1].each{|arg| if arg == "--" then arr = rhs_keys else arr << arg end } if lhs_keys.empty? then $stderr.puts "No keys given for LHS: using all fields as key." end if lhs_keys.empty? then $stderr.puts "No keys given for RHS: using all fields as key." end return {:lhs => lhs, :rhs => rhs, :output => out, :policy => policy, :cache => cache, :lhs_keys => lhs_keys, :rhs_keys => rhs_keys } end # Load config config = process_commandline_args # TODO: support compound keys from the command line lhs = KeyValueCSV.new(config[:lhs], config[:lhs_keys]) rhs = KeyValueCSV.new(config[:rhs], config[:rhs_keys]) merge = eval("MergePolicy::#{config[:policy]}.new(lhs, rhs)") puts "Merging #{lhs} into #{rhs} with policy '#{merge}'" puts "" puts "Fields (*keys):" puts " LHS: #{lhs.fields.map{|f| lhs.keys.include?(f) ? '*'+f : f}.join(', ')}" puts " RHS: #{rhs.fields.map{|f| rhs.keys.include?(f) ? '*'+f : f}.join(', ')}" puts "Output: #{merge.fields.join(', ')}" puts "" # puts "\nCounting records in each (and validating CSV)" # puts " LHS: #{lhs.count}" # puts " RHS: #{rhs.count}" # # $stderr.puts "WARNING: RHS file is much larger. Consider reversing the order of files if you are performing a symmetric join." if rhs.count > lhs.count # # puts "Finding Minimal Key Lengths for #{rhs}..." # rhs.minimal_keys.each{|k, v| # puts " KEY #{rhs}: #{k} => #{v}" # } # # # puts "Key size is #{rhs.key_size}B, with #{rhs.count} records this means #{(((rhs.key_size + [rhs.count].pack('l').size)*rhs.count)/1024/1024).round(2)}MB needed for index." rhs.cache = eval("CacheMethods::#{config[:cache]}.new") ############## Perform Merge ################################# count = 0 CSV.open(config[:output], 'w') do |out_csv| out_csv << merge.fields puts "Building output CSV..." # Open a transaction for the rhs file, # in readiness for reading from keys rhs.seek_retrieval{ # The one we don't have the index for CSV.foreach(lhs.filename, :encoding => 'utf-8', :headers => true) do |lhs_row| # Generate a key from the row key = lhs.get_minimal_key(lhs_row) # Look up the value from the LHS cache # This uses file seeking, so is quickish # and low on memory rhs_vals = rhs[key] || {} # Ensure the RHS vals are in hash form lhs_vals = lhs_row.to_hash # Merge according to policy and output out_csv << merge.merge_line(lhs_vals, rhs_vals) if merge.accept_line?(lhs_vals, rhs_vals) print "\rLine: #{count} " if (count+=1) % OUTPUT_DIVISOR == 0 end } end print "\rLine: #{count} " # Ensure we always print the last line number for clarity print "\n" # End puts "Done." exit
class GroupsController < ApplicationController def index # query values limit = (params[:limit] || 20).to_i page = (params[:page] || 1).to_i groups = if params[:trending].present? Group.trending(current_user).page(page).per(limit).groups elsif params[:user_id].present? User.find(params[:user_id]).groups.order('id ASC').page(page).per(limit) else Group.order('created_at DESC').limit(limit) end respond_to do |format| format.json do render json: groups, meta: {cursor: 1 + page} end format.html do render_ember groups end end end ember_action(:show, true) { Group.find(params[:id]) } def new authenticate_user! render_ember end def create authenticate_user! group_hash = params.require(:group).permit(:name, :bio, :about).to_h return error! "Group with that name already exists", 409 if Group.exists?(['lower(name) = ?', group_hash['name'].downcase]) group = Group.new_with_admin(group_hash, current_user) if group.save render json: group, status: :created else return error! group.errors.full_messages, 400 end end def update authenticate_user! group = Group.find(params[:id]) group_hash = params.require(:group).permit(:bio, :about, :cover_image_url, :avatar_url).to_h if current_user.admin? || group.member(current_user).admin? # cleanup image uploads if they are bad group_hash['cover_image'] = group_hash.delete('cover_image_url') group_hash.delete('cover_image') unless group_hash['cover_image'] =~ /^data:image/ group_hash['avatar'] = group_hash.delete('avatar_url') group_hash.delete('avatar') unless group_hash['avatar'] =~ /^data:image/ group.attributes = group_hash group.save! render json: group else return error! "Only admins can edit the group", 403 end end def destroy authenticate_user! # Only site admins should be able to delete # Sorry users, once you make a group it's part of the commons. if current_user.admin? group = Group.find(params[:id]) group.delay.destroy render json: {} else return error! "Only Hummingbird administrators can delete groups", 403 end end end
class Photo < ActiveRecord::Base validates_presence_of :title, :content after_create :create_event before_destroy :destroy_event include TheComments::Commentable include Likeable belongs_to :user belongs_to :album belongs_to :blog belongs_to :novelty has_many :photo_sources, dependent: :destroy has_many :blogs, through: :photo_sources, source: :photoable, source_type: 'Blog' has_many :novelties, through: :photo_sources, source: :photoable, source_type: 'New' has_many :events, as: :eventable def create_event e = Event.new e.eventable = self e.user = self.user e.save end def destroy_event e = self.events e.destroy_all end def commentable_title "Undefined Post Title" end def commentable_url "#" end def commentable_state "published" end end
class Auction < ActiveRecord::Base belongs_to :user has_many :bids, dependent: :destroy validates_presence_of :title validates :reserve_price, presence: true, numericality: {greater_than_or_equal_to: 1} default_scope order("created_at DESC") scope :published, -> { where(state: :published) } after_initialize :set_default_current_price state_machine :state, initial: :draft do event :publish do transition draft: :published end event :reserve do transition published: :reserve_met end end private def set_default_current_price self.current_price ||= 0 end #validate :add_to_bids # def add_to_bids # if self.bids.price < self.current_price #end end
class EasyTimeEntryBaseQuery < EasyQuery def self.permission_view_entities :view_time_entries end def query_after_initialize super self.sort_criteria = {'0'=>['spent_on', 'asc']} if self.sort_criteria.blank? self.display_project_column_if_project_missing = false end def available_filters return @available_filters unless @available_filters.blank? group = l(:label_filter_group_easy_time_entry_query) @available_filters = { 'spent_on' => {:type => :date_period, :order => 1, :group => group}, 'activity_id' => {:type => :list, :order => 10, :values => Proc.new{TimeEntryActivity.shared.active.collect{|i| [i.name, i.id.to_s]}}, :group => group}, 'tracker_id' => {:type => :list, :order => 11, :values => (project ? Proc.new{project.trackers.collect{|t| [t.name, t.id.to_s]}} : Proc.new{ Tracker.all.collect{|t| [t.name, t.id.to_s]} }), :group => group} } unless project @available_filters['xproject_id'] = { :type => :list_optional, :order => 5, :values => Proc.new{self.projects_for_select}, :group => group, :name => l(:field_project)} @available_filters['parent_id'] = { :type => :list, :order => 6, :values => Proc.new{self.projects_for_select}, :group => group} @available_filters['project_root_id'] = { :type => :list, :order => 7, :values => Proc.new{self.projects_for_select(Project.visible.roots.select([:id, :name, :easy_level]).all, false)}, :group => group} end if User.current.allowed_to_globally?(:view_all_statements, {}) @available_filters['user_id'] = { :type => :list, :order => 15, :values => Proc.new do users = User.active.non_system_flag.easy_type_internal.sorted.collect{|i| [i.name, i.id.to_s]} users.unshift(["<< #{l(:label_me)} >>", 'me']) if User.current.logged? users end, :group => group } end @available_filters['user_roles'] = { :type => :list, :order => 9, :values => Proc.new{Role.givable.collect {|r| [r.name, r.id.to_s]}}, :group => group} add_custom_fields_filters(TimeEntryCustomField) add_associations_custom_fields_filters :project @available_filters end def available_columns unless @available_columns_added @available_columns = [ EasyQueryColumn.new(:spent_on, :sortable => "#{TimeEntry.table_name}.spent_on", :groupable => true), EasyQueryColumn.new(:user, :groupable => true, :sortable => ["#{User.table_name}.lastname", "#{User.table_name}.firstname", "#{User.table_name}.id"]), EasyQueryColumn.new(:activity, :groupable => true, :sortable => "#{TimeEntryActivity.table_name}.name"), EasyQueryColumn.new(:issue, :sortable => "#{Issue.table_name}.subject", :groupable => true), EasyQueryColumn.new(:tracker), EasyQueryColumn.new(:project, :sortable => "#{Project.table_name}.name", :groupable => true), EasyQueryColumn.new(:project_root, :sortable => "(SELECT p.id FROM #{Project.table_name} p WHERE p.lft <= #{Project.table_name}.lft AND p.rgt >= #{Project.table_name}.rgt AND p.parent_id IS NULL)", :sumable_sql => "(SELECT p.id FROM #{Project.table_name} p WHERE p.lft <= #{Project.table_name}.lft AND p.rgt >= #{Project.table_name}.rgt AND p.parent_id IS NULL)", :groupable => true), # :sumable_sql => "(SELECT r.role_id FROM member_roles r INNER JOIN members m ON m.id = r.member_id WHERE m.project_id = #{TimeEntry.table_name}.project_id AND m.user_id = #{TimeEntry.table_name}.user_id)" EasyQueryColumn.new(:user_roles, :groupable => false), EasyQueryColumn.new(:comments), EasyQueryColumn.new(:hours, :sortable => "#{TimeEntry.table_name}.hours", :sumable => :bottom, :caption => 'label_spent_time'), EasyQueryColumn.new(:estimated_hours, :sortable => "#{Issue.table_name}.estimated_hours", :sumable => :bottom, :sumable_sql => "(SELECT i.estimated_hours FROM #{Issue.table_name} i WHERE i.id = #{TimeEntry.table_name}.issue_id)", :sumable_options=>{:distinct_columns => [["#{Issue.table_name}.id", :issue]]}), EasyQueryColumn.new(:easy_range_from), EasyQueryColumn.new(:easy_range_to), EasyQueryColumn.new(:created_on), EasyQueryColumn.new(:updated_on) ] @available_columns << EasyQueryColumn.new(:issue_id, :sortable => "#{Issue.table_name}.id") if EasySetting.value('show_issue_id', project) @available_columns += TimeEntryCustomField.visible.all.collect {|cf| EasyQueryCustomFieldColumn.new(cf)} @available_columns += ProjectCustomField.visible.all.collect{|cf| EasyQueryCustomFieldColumn.new(cf, :assoc => :project)} @available_columns_added = true end @available_columns end def columns_with_me super + ['user_id'] end def entity TimeEntry end def entity_scope TimeEntry.non_templates.visible end def default_find_include [:project, :user, :issue, :activity] end def default_sort_criteria ['spent_on'] end def get_custom_sql_for_field(field, operator, value) case field when 'activity_id' db_table = TimeEntry.table_name db_field = 'activity_id' sql = "#{db_table}.activity_id #{ operator == '=' ? 'IN' : 'NOT IN' } (SELECT #{TimeEntryActivity.table_name}.id FROM #{TimeEntryActivity.table_name} WHERE #{TimeEntryActivity.table_name}.parent_id = '#{value}' OR " sql << sql_for_field(field, '=', value, db_table, db_field) + ')' return sql when'user_roles' v = value.is_a?(Array) ? value.join(',') : value o = (operator == '=') ? 'IN' : 'NOT IN' sql = "EXISTS (SELECT r.id FROM member_roles r INNER JOIN members m ON m.id = r.member_id WHERE m.user_id = #{User.table_name}.id AND m.project_id = #{TimeEntry.table_name}.project_id AND r.role_id #{o} (#{v}))" return sql when 'project_root_id' db_table = TimeEntry.table_name db_field = 'project_id' v = "SELECT #{Project.table_name}.id FROM #{Project.table_name} WHERE " if value.is_a?(Array) projects = Project.find(value) v << projects.collect{|p| Project.allowed_to_condition(User.current, :view_all_statements, {:project => p, :with_subprojects => Setting.display_subprojects_issues?})}.join(' OR ') else v << Project.visible.allowed_to_condition(User.current, :log_time, {:project => Project.find(value), :with_subprojects => Setting.display_subprojects_issues?}) end o = (operator == '=') ? 'IN' : 'NOT IN' sql = "#{db_table}.#{db_field} #{ operator == '=' ? 'IN' : 'NOT IN' } (#{v})" return sql when 'parent_id' op_not = (operator_for('parent_id') == '!') return "#{Project.table_name}.id #{op_not ? 'NOT IN' : 'IN'} (SELECT p_parent_id.id FROM #{Project.table_name} p_parent_id WHERE p_parent_id.parent_id IN (#{values_for('parent_id').join(',')}))" end end def sql_for_xproject_id_field(field, operator, v) db_table = self.entity.table_name db_field = 'project_id' returned_sql_for_field = self.sql_for_field(db_field, operator, v, db_table, db_field) return ('(' + returned_sql_for_field + ')') unless returned_sql_for_field.blank? end def sql_for_tracker_id_field(field, operator, v) db_table = Issue.table_name db_field = field returned_sql_for_field = self.sql_for_field(field, operator, v, db_table, db_field) return ('(' + returned_sql_for_field + ')') unless returned_sql_for_field.blank? end def sql_for_activity_id_field(field, operator, value) condition_on_id = sql_for_field(field, operator, value, Enumeration.table_name, 'id') condition_on_parent_id = sql_for_field(field, operator, value, Enumeration.table_name, 'parent_id') ids = value.map(&:to_i).join(',') table_name = Enumeration.table_name if operator == '=' "(#{table_name}.id IN (#{ids}) OR #{table_name}.parent_id IN (#{ids}))" else "(#{table_name}.id NOT IN (#{ids}) AND (#{table_name}.parent_id IS NULL OR #{table_name}.parent_id NOT IN (#{ids})))" end end end
class RemoveAncestryDetailsFromTasks < ActiveRecord::Migration def change remove_column :tasks, :ancestry_depth, :integer, :default => 0 remove_index :tasks, :ancestry remove_column :tasks, :ancestry, :string end end
class FormSubjectsController < ApplicationController before_filter :check_autentication, only: [:edit, :update, :destroy] layout "page" # GET /form_subjects # GET /form_subjects.json def index @form_subjects = FormSubject.all respond_to do |format| format.html # index.html.erb format.json { render json: @form_subjects } end end # GET /form_subjects/1 # GET /form_subjects/1.json def show @form_subject = FormSubject.find(params[:id]) @num_ans = @form_subject.form_answers.count end # GET /form_subjects/new # GET /form_subjects/new.json def new @form_subject = FormSubject.new respond_to do |format| format.html # new.html.erb format.json { render json: @form_subject } end end # GET /form_subjects/1/edit def edit @form_subject = FormSubject.find(params[:id]) end # POST /form_subjects # POST /form_subjects.json def create if current_user.present? @form_subject = FormSubject.new(params[:form_subject]) @form_subject.user_id = current_user.id @save = @form_subject.save end end # PUT /form_subjects/1 # PUT /form_subjects/1.json def update @form_subject = FormSubject.find(params[:id]) @updated = @form_subject.update_attributes(params[:form_subject]) end # DELETE /form_subjects/1 # DELETE /form_subjects/1.json def destroy @form_subject = FormSubject.find(params[:id]) @form_subject.destroy respond_to do |format| format.html { redirect_to form_subjects_url } format.js end end end
class User < ActiveRecord::Base ROLES = %w(non_member member admin) validates :username, :kind, presence: true has_many :posts, dependent: :destroy def admin? ROLES[kind] == 'admin' end def member? ROLES[kind] == 'member' end def non_member? ROLES[kind] == 'non_member' end def self.authentication(login) User.where(:username => login.to_s).first end end
class CreateJobs < ActiveRecord::Migration def change create_table :jobs do |t| t.string :title t.string :company_name t.integer :occupation, default: 0 t.integer :job_type, default: 0 t.string :location t.string :url t.text :description t.text :apply_information t.integer :user_id, null: false t.timestamps null: false end end end
When /^I confirm my email$/ do get "/confirmation?token=#{@user.perishable_token}" assert_response :redirect assert_redirected_to dashboard_url follow_redirect! end Then /^a new user with the email "(.*)" should be created$/ do |email| @user = User.find_by_email(email) assert_not_nil @user end Then /^the signup form should be shown again$/ do assert_template "users/new" end Then /^I should\s?((?:not)?) be registered$/ do |present| assert_nil User.find_by_email("francine@yoyoma.com") end Then /^I should be forbidden$/ do assert @forbidden end Then /^an email with the subject "(.*)" should be sent to me$/ do |subject| assert_sent_email do |email| @user.blank? || email.to.include?(me.email) email.subject =~ /#{subject}/i end end Then /^my email should be confirmed$/ do @user.reload assert @user.confirmed? end
module Locomotive module Liquid module Tags # Carousel a collection # Carousel is like a paginate, but it includes all pages for client-side switching # Usage: # # {% carousel contents.projects by 5 %} # #myCarousel.carousel.slide # {{ carousel.prev_link }} # .carousel-inner # {% for page in carousel.pages %} # %div(class="item {% if page.selected %}selected{% endif %}") # {% for project in page.collection %} # {{ project.name }} # {% endfor %} # {% endfor %} # {{ carousel.next_link }} # {% endpaginate %} class Carousel < ::Liquid::Block Syntax = /(#{::Liquid::Expression}+)\s+by\s+([0-9]+)/ def initialize(tag_name, markup, tokens, context) if markup =~ Syntax @collection_name = $1 @per_page = $2.to_i else raise ::Liquid::SyntaxError.new("Syntax Error in 'carousel' - Valid syntax: paginate <collection> by <number>") end super end def render(context) context.stack do collection = context[@collection_name] raise ::Liquid::ArgumentError.new("Cannot carousel array '#{@collection_name}'. Not found.") if collection.nil? name = @collection_name.split(".").last params_page = context["params.#{name}_page"] || 1 current_page = 1 path = sanitize_path(context['fullpath']) num_pages = 0 carousel = { :pages => [].tap do |ret| coll = collection.is_a?(Array) ? collection : collection.send(:collection) coll.each_slice(@per_page) {|x| num_pages += 1 } coll.each_slice(@per_page) do |page| ret << { :current_page => current_page, :selected => (params_page == current_page), :first => (current_page == 1), :last => (current_page == num_pages), :collection => page }.stringify_keys! current_page += 1 end end, :num_pages => num_pages, :previous_page => (current_page - 1), :next_page => (current_page + 1), :per_page => @per_page }.stringify_keys! context['carousel'] = carousel render_all(@nodelist, context) end end private def sanitize_path(path) _path = path.gsub(/page=[0-9]+&?/, '').gsub(/_pjax=true&?/, '') _path = _path.slice(0..-2) if _path.last == '?' || _path.last == '&' _path end end ::Liquid::Template.register_tag('carousel', Carousel) end end end
module MyServiceName module Helpers module Authenticator NoApiKeysConfigured = Class.new(StandardError) def self.call(auth_keys:, submitted_key:) if auth_keys.nil? || auth_keys.empty? raise NoApiKeysConfigured, 'Please configure API_KEYS environment variable (see the README.md).' end submitted_key && !submitted_key.strip.empty? && auth_keys.split(',').include?(submitted_key) end end end end
require 'test_helper' class EventsControllerTest < ActionController::TestCase # Replace this with your real tests. context "cities action" do should "return subcategories of some place" do @ev = Place.make :title => 'xxx' @child = Place.make :parent_id => @ev.id, :title => 'asdf' get :cities, :events => { :root_place => @ev.id }.stringify_keys obj = JSON.parse(@response.body) assert obj.is_a?(Array) assert_equal 1, obj.size assert_equal({ :label => 'asdf', :id => @child.id }.stringify_keys, obj.first) end should "return json array if no category exist" do Place.delete_all get :cities obj = JSON.parse(@response.body) assert obj.is_a?(Array) assert_equal 0, obj.size end context "with empty_text set" do setup do @default_object = { :label => 'Любой город', :id => 0 }.stringify_keys end should "return subcategories of some place" do @ev = Place.make :title => 'xxx' @child = Place.make :parent_id => @ev.id, :title => 'asdf' get :cities, :events => { :root_place => @ev.id }.stringify_keys, :empty_text => true obj = JSON.parse(@response.body) assert obj.is_a?(Array) assert_equal 2, obj.size assert_equal( [@default_object, { :label => 'asdf', :id => @child.id }.stringify_keys], obj ) end should "return json array if no category exist" do Place.delete_all get :cities, :empty_text => true obj = JSON.parse(@response.body) assert obj.is_a?(Array) assert_equal 1, obj.size assert_equal @default_object, obj.first end end end context "subjects action" do should "return subcategories of some place" do @ev = Subject.make :title => 'xxx' @child = Subject.make :parent_id => @ev.id, :title => 'asdf' get :subjects, :events => { :root_subject => @ev.id }.stringify_keys obj = JSON.parse(@response.body) assert obj.is_a?(Array) assert_equal 1, obj.size assert_equal({ :label => 'asdf', :id => @child.id }.stringify_keys, obj.first) end should "return json array if no category exist" do Place.delete_all get :subjects obj = JSON.parse(@response.body) assert obj.is_a?(Array) assert_equal 0, obj.size end context "with empty_text set" do setup do @default_object = { :label => 'Любая специализация', :id => 0 }.stringify_keys end should "return subcategories of some place with empty_text" do @ev = Subject.make :title => 'xxx' @child = Subject.make :parent_id => @ev.id, :title => 'asdf' get :subjects, :events => { :root_subject => @ev.id }.stringify_keys, :empty_text => true obj = JSON.parse(@response.body) assert obj.is_a?(Array) assert_equal 2, obj.size assert_equal( [@default_object, { :label => 'asdf', :id => @child.id }.stringify_keys], obj ) end should "return json array if no category exist" do Place.delete_all get :subjects, :empty_text => true obj = JSON.parse(@response.body) assert obj.is_a?(Array) assert_equal 1, obj.size assert_equal @default_object, obj.first end end end context "index action" do should "contain titles" do Event.delete_all Event.make :title => 'xxx1<', :image_file_name => 'img1&lt;', :event_type_id => EventType.make(:title => 'secret title') Event.make :title => 'xxx2', :image_file_name => 'img2' get :index assert_jquery_datepicker_loaded #should contain titles assert_contains_n_times @response.body, 'xxx1&lt;', 1 assert_contains_n_times @response.body, 'xxx2', 1 #should contain links to items assert_contains_n_times @response.body, event_path(Event.first), 1 assert_contains_n_times @response.body, event_path(Event.last), 1 #should contain image links assert_contains_n_times @response.body, 'img1&lt;', 1 assert_contains_n_times @response.body, 'img2', 1 #should contain event_type assert_contains_n_times @response.body, 'secret title', 1 end should "show 5 items per page" do Event.delete_all 21.times do Event.make end get :index assert_select '.item', 5 assert_correct_search_form_action assert_jquery_datepicker_loaded assert_javascript_loaded 'events-index' get :index, :page => 4 assert_select '.item', 5 assert_correct_search_form_action get :index, :page => 5 assert_select '.item', 1 assert_correct_search_form_action get :index, :page => 6 assert_select '.item', 0 assert_correct_search_form_action end should "show 5 items per page when from and to params given" do Event.delete_all 21.times do Event.make :start_time => Date.today.to_datetime end p = { :from => (Date.today - 2.days).to_datetime, :to => (Date.today + 2.days).to_datetime } get :index, p assert_select '.item', 5 assert_correct_search_form_action assert_jquery_datepicker_loaded assert_javascript_loaded 'events-index' get :index, p.merge(:page => 4) assert_select '.item', 5 assert_correct_search_form_action get :index, p.merge(:page => 5) assert_select '.item', 1 assert_correct_search_form_action get :index, p.merge(:page => 6) assert_select '.item', 0 assert_correct_search_form_action end should "show pagination" do Event.delete_all 20.times do Event.make end get :index assert_contains_pagination assert_jquery_datepicker_loaded assert_javascript_loaded 'events-index' end should "show correct message if cost is zero" do Event.delete_all Event.make :cost => nil get :index assert_contains_n_times @response.body, "666666", 0 assert_contains_n_times @response.body, "Бесплатное посещение", 1 end should "show cost for each item" do Event.delete_all Event.make :cost => 666666 get :index assert_contains_n_times @response.body, "666666", 1 assert_contains_n_times @response.body, "Бесплатное посещение", 0 end should "show event dates" do Event.delete_all Event.make :start_time => Date.new(1989, 05, 22).to_datetime Event.make :start_time => Date.new(1989, 05, 22).to_datetime, :end_time => Date.new(1989, 05, 22).to_datetime Event.make :start_time => Date.new(1941, 06, 22).to_datetime, :end_time => Date.new(1941, 06, 23).to_datetime Event.make :start_time => Date.new(1945, 05, 9).to_datetime, :end_time => Date.new(1945, 06, 01).to_datetime get :index assert_contains_n_times @response.body, '22 мая 1989 года', 2 assert_contains_n_times @response.body, '22 - 23 июня 1941 года', 1 assert_contains_n_times @response.body, '09 мая - 01 июня 1945 года', 1 end should "contain events place" do Event.delete_all @place = Place.make :title => "Some big place<>" Event.make :place => @place get :index assert_contains_n_times @response.body, "Some big place&lt;&gt;", 1 end should "contain default string if no place given" do Event.delete_all Event.make :place => Place.make Event.update_all 'place_id' => nil get :index assert_contains_n_times @response.body, "неизвестно", 1 end end context "new action" do should "contain needed javascripts" do login get :new assert_jquery_datepicker_loaded assert_jquery_selectchain_loaded assert_javascript_loaded 'events' end end context "search action" do should "contain needed javascripts" do get :search assert_jquery_datepicker_loaded assert_jquery_selectchain_loaded assert_javascript_loaded 'events-search' assert_select 'form[action=?]', '/events/search' end should "call correct search method" do mock(Event).search(nil, 1, 3, 4, 2, 5, 6, nil, nil) get :search, :events => { :root_subject => 1, :root_place => 2 }, :event => { :subject_id => 3, :event_type_id => 4, :place_id => 5 }, :event_free => 6, :commit => true end end context "my action" do should "be displayed when logged in" do login get :my assert_response :success end should "act correctly when not logged in" do get :my assert_require_login end should "display message when no items added" do Event.delete_all login get :my assert_response_contains 'Не найдено событий по Вашему запросу.', 1 assert_select "a[href=?]", new_event_path, { :count => 1, :text => "добавить событие" } end end context "protected methods" do should "correctly parse date" do get :index assert_equal Date.new(2010, 5, 7), @controller.send(:parse_date, '07.05.2010') end end end
require 'spec_helper' describe MoviesController do before(:all) do 10.times do |n| FactoryGirl.create(:movie) end end it "should display a list of the latest movies as the default" do get :index, :page => 1 expect(assigns(:movies)).to eq(Movie.latest.page(1).per(10)) end it "should display a movie selected" do get :show, :id => Movie.first.slug expect(assigns(:movie)).to eq(Movie.first) end end
class AddItemToProfiles < ActiveRecord::Migration[6.0] def change add_column :profiles, :gender, :integer add_column :profiles, :age, :integer end end
# class Rdf::Owl::RestrictionsController < ApplicationController # include Cms::BaseFilter # include Cms::CrudFilter # # model Rdf::Owl::Restriction # # navi_view "cms/main/navi" # # before_action :set_class # # private # def set_vocab # return if @vocab.present? # @vocab = Rdf::Vocab.site(@cur_site).find(params[:vid]) # raise "404" unless @vocab # end # # def set_class # set_vocab # return if @rdf_class.present? # @rdf_class = Rdf::Class.vocab(@vocab).find(params[:class_id]) # raise "404" unless @rdf_class # end # # def fix_params # set_vocab # set_class # { in_vocab: @vocab, in_class: @rdf_class } # end # # def set_crumbs # set_vocab # set_class # @crumbs << [:"rdf.vocabs", rdf_vocabs_path] # @crumbs << [@vocab.labels.preferred_value, rdf_vocab_path(id: @vocab)] # @crumbs << [@rdf_class.name, rdf_classes_class_path(vid: @vocab, id: @rdf_class)] # end # # def set_item # set_vocab # set_class # @item = @rdf_class.properties.find(params[:id]) # @item.attributes = fix_params # end # # public # def index # set_vocab # set_class # raise "403" unless @vocab.allowed?(:read, @cur_user, site: @cur_site, node: @cur_node) # # @items = @rdf_class.properties.search(params[:s]).order_by(_id: 1).page(params[:page]).per(50) # end # # def show # raise "403" unless @vocab.allowed?(:read, @cur_user, site: @cur_site, node: @cur_node) # render # end # # def new # @item = @rdf_class.properties.new pre_params.merge(fix_params) # raise "403" unless @vocab.allowed?(:edit, @cur_user, site: @cur_site, node: @cur_node) # end # # def create # @item = @rdf_class.properties.create get_params # render_create @item.valid? # end # # def edit # raise "403" unless @vocab.allowed?(:edit, @cur_user, site: @cur_site, node: @cur_node) # render # end # # def update # @item.attributes = get_params # @item.in_updated = params[:_updated] if @item.respond_to?(:in_updated) # raise "403" unless @vocab.allowed?(:edit, @cur_user, site: @cur_site, node: @cur_node) # render_update @item.update # end # # def delete # raise "403" unless @vocab.allowed?(:delete, @cur_user, site: @cur_site, node: @cur_node) # render # end # # def destroy # raise "403" unless @vocab.allowed?(:delete, @cur_user, site: @cur_site, node: @cur_node) # render_destroy @item.destroy # end # end
describe Movies::UseCases::Index do let(:params) { {} } let(:call_class) { described_class.new(params: params).call } before do create_list(:movie, 10) end it 'returns 5 records' do params[:offset] = 0 params[:limit] = 5 expect(call_class.count).to eq(5) end it 'returns all records' do expect(call_class.count).to eq(10) end end
# frozen_string_literal: true module Api # Base Api Controller class BaseController < ActionController::Base protect_from_forgery with: :null_session include JSONAPI::Deserialization include Knock::Authenticable def render_json(serializer_instance) render json: serializer_instance.serializable_hash end # handle invalid JWT token def unauthorized_entity(_entity_name) render_json Exceptions::NotAuthorized.new({}) end end end
class ApplicationMailer < ActionMailer::Base default from: "noreply.esv@gmail.com" layout "mailer" end
class Trailer < ActiveRecord::Base def self.released where('release_date <= ?', Date.today.year).order('release_date desc') end end
class SetMemberNicknameDefaultToBlank < ActiveRecord::Migration def change change_column :members, :namenick, :string, :default => "" end end
class DiseasesController < ApplicationController layout 'internal' before_action :authenticate_user! before_action :block_crossprofile_access before_action :recover_profile def index @diseases = @profile.diseases end def new end def edit @disease = Disease.find(params[:id]) end def create @disease = Disease.new(disease_params) @disease.profile = @profile if @disease.save flash[:success] = "Disease registered sucessfully" redirect_to profile_diseases_path(profile_email: @profile.email) else render 'new' end end def update @disease = Disease.find(params[:id]) if @disease.update(disease_params) flash[:success] = "Disease updated sucessfully" redirect_to profile_diseases_path(profile_email: @disease.profile.email) else render 'edit' end end def destroy @disease = Disease.find(params[:id]) profile_email = @disease.profile.email @disease.destroy redirect_to profile_diseases_path(profile_email: profile_email) end private def disease_params params.require(:disease).permit(:name, :cause, :description, :start, :finish) end end
module WebEx module Events class EventSummaryRequest WEBEX_EMPTY_RESULTS_EXCEPTION_ID = "000015" attr_accessor :start_date, :end_date def initialize(options = {}) @start_date, @end_date = options[:start_date], options[:end_date] end def find_events! events = xml_response.xpath('//event').map do |node| Event.from_xml(node.to_xml) end EventList.new(events) end def payload <<-XML <?xml version="1.0" encoding="UTF-8"?> <message xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <header> <securityContext> <webExID>#{Configuration.username}</webExID> <password>#{Configuration.password}</password> <siteID>#{Configuration.site_id}</siteID> <partnerID>#{Configuration.partner_id}</partnerID> </securityContext> </header> <body> <bodyContent xsi:type="java:com.webex.service.binding.event.LstsummaryEvent"> <listControl> <startFrom/> </listControl> <order> <orderBy>STARTTIME</orderBy> </order> <dateScope> <startDateStart>#{formatted_date start_date}</startDateStart> <endDateEnd>#{formatted_date end_date}</endDateEnd> <timeZoneID>#{::WebEx::Events::TimeWithZone::UTC_ZONE_ID}</timeZoneID> </dateScope> </bodyContent> </body> </message> XML end private def response @response ||= HTTParty.post(Configuration.xml_service_url, body: payload) end def xml_response @xml_response ||= begin xml = Nokogiri::XML(response.body) webex_exception = xml.at_xpath('//serv:exceptionID') if webex_exception && webex_exception.content != WEBEX_EMPTY_RESULTS_EXCEPTION_ID raise "WebEx Error: #{xml.at_xpath('//serv:reason').content}" end xml.remove_namespaces! end end def formatted_date(date) date.utc.strftime('%m/%d/%Y %H:%M:%S') if date end end end end
require 'test_helper' require 'exchange_rates_api_service' require 'validation_helper' class ExchangeRateApiServiceTest < ActiveSupport::TestCase def setup @api = ExchangeRatesApiService.new end test "raise error on base length != 3" do check_for_error "US" end test "raise error on base lower case" do check_for_error "rub" end test "raise error on base not string" do check_for_error 23 check_for_error Hash.new check_for_error nil end private def check_for_error(value) assert_raises ValidationHelper::ValidationError do @api.get_currency! value end end end
class Picture < ApplicationRecord belongs_to :user has_many :favorites, dependent: :destroy has_many :favorite_users, through: :favorites, source: :user mount_uploader :image, PictureImageUploader attr_accessor :action_required validates :image_or_content, presence: true private def image_or_content image.presence or content.presence end end