text
stringlengths
10
2.61M
class FieldType attr_accessor :name,:type,:width,:precision def initialize(name,type,width,precision) @name = name @type = type @width = width @precision = precision end def to_s "#{@name},#{@type},#{@width},#{@precision}" end end class Table attr_accessor :name,:fields def initialize(name) @name = name @fields = [] end def create_field(name,type,width,precision) field = FieldType.new(name,type,width,precision) @fields << field return field end def to_s value = [] value << "#{@name},#{@fields.size}" @fields.each do |i| value << i.to_s end return value.join("\n") end def clone() t = Table.new(@name) t.fields = @fields return t end end class FPoint @@template = <<HERE %<objectid>d %<layerid>s %<layername>s %<num>d %<point>s HERE attr_accessor :objectid,:layerid,:layername,:geometry def initialize(objectid,layerid,layername,point) @layerid = layerid @layername = layername @objectid = objectid @geometry = point @attribute= {:objectid => @objectid, :layerid => @layerid, :layername=> @layername, :num => 1, :point => @geometry} end def to_s sprintf(@@template,@attribute) end end class FLine @@template = <<HERE %<objectid>d %<layerid>s %<layername>s %<type>s %<num>d %<point>s HERE attr_accessor :objectid,:layerid,:layername,:geometry def initialize(objectid,layerid,layername,points) @objectid = objectid @layerid = layerid @layername = layername @geometry = points @attr = {:objectid => @objectid, :layerid => @layerid, :layername=> @layername, :type => 1, :num => @geometry.size, :point => @geometry} end def to_s sprintf(@@template,@attr) end end class FPolygon @@template = <<HERE %<objectid>d %<layerid>s %<layername>s %<point>s %<num>d %<line>s HERE attr_accessor :objectid,:layerid,:layername,:geometry def initialize(objectid,layerid,layername,lines) @objectid = objectid @layerid = layerid @layername = layername @geometry = lines @attr = {:objectid => @objectid, :layerid => @layerid, :layername=> @layername, :point => Point.new(1,1), :num => @geometry.size, :line => @geometry} end def to_s sprintf(@@template,@attr) end end class Attribute def initialize(objectid,layerid,other) @objectid = objectid @layerid = layerid @other = other end def to_s "#{@objectid},#{@layerid},#{@other.join(',')}" end end class Layer attr_accessor :id,:name,:type,:table,:field,:feats; def initialize(id,name,type,table,tabledefn) @id = id @name = name @type = type @table = table @field = tabledefn @field.name = table @feats = [] end def create_feature(geo,attri) feat = VctFeature.new(geo.objectid,geo,attri) @feats << feat return feat end def to_s "#{@id},#{@name},#{@type},0,0,0,#{@table}" end end class VctFeature attr_accessor :id,:geometry,:attribute def initialize(id,geo,attri) @geometry = geo @attribute = attri @id = id end def to_s "id=:#{@id}\ngeometry=:\n#{@geometry}field=:#{@attribute}\n===" end end class VctDataset attr_accessor :layers,:name,:srs def initialize(name) @name = name @layers = [] @prefix = {:name => 'layer', :id => '100', :table=> 'table'} @layercode = 0 end def create_layer(type,tabledefn) @layercode = @layercode +1 layer = Layer.new(@prefix[:id] + @layercode.to_s, @prefix[:name] + @layercode.to_s, type, @prefix[:table] + @layercode.to_s, tabledefn) @layers << layer return layer end def getLayerSize @layers.size end def to_s "#{@name}:\n,#{@layers.join("\n")}" end end
#encoding: utf-8 class PKCS7Encoder < ActiveRecord::Base # attr_accessible :title, :body def self.decode(text) pad = text[-1].ord pad = 0 if (pad < 1 || pad > 32) size = text.size - pad text[0...size] end # 对需要加密的明文进行填充补位 # 返回补齐明文字符串 def self.encode(text) # 计算需要填充的位数 amount_to_pad = 32 - (text.length % 32) amount_to_pad = 32 if amount_to_pad == 0 # 获得补位所用的字符 pad_chr = amount_to_pad.chr "#{text}#{pad_chr * amount_to_pad}" end end
class Manager < ActiveRecord::Base attr_accessible :name has_many :castings end
class Chat < ApplicationRecord has_many :chat_subscribers, dependent: :destroy has_many :users, through: :chat_subscribers has_many :messages, dependent: :destroy end
require 'rails_helper' RSpec.describe User, type: :model do describe 'associations' do it { is_expected.to have_many(:authentications).dependent(:destroy) } end describe 'validations' do let(:user) { build(:user) } context 'when user valid' do it { expect(user).to be_valid } end context 'when user invalid' do it 'name blank' do user.name = nil expect(user).not_to be_valid end it 'email blank' do user.email = nil expect(user).not_to be_valid end end end describe 'scope with_unreviewed_cards' do let(:user) { create(:user) } let(:second_user) { create(:user, name: 'second', email: 'second@cer.ru') } let(:pack_second) { create(:pack, name: 'second', user: user) } let(:pack_third) { create(:pack, name: 'third', user: second_user) } let(:card_second) { create(:card, original_text: 'second', pack: pack_second) } let(:card_third) { create(:card, original_text: 'third', pack: pack_third) } before do card_second.pack.user.update(current_pack_id: card_second.pack.id) card_third.pack.user.update(current_pack_id: card_third.pack.id) card_second.update(review_date: Time.zone.now - 1.day) card_third.update(review_date: Time.zone.now + 1.minute) end context 'when true' do it 'return user with card for review' do expect(User.with_unreviewed_cards).to match_array(card_second.pack.user) end end context 'when false' do it 'user with card not for review' do expect(User.with_unreviewed_cards).not_to match_array(card_third.pack.user) end end end end
source 'https://rubygems.org' git_source(:github) do |repo_name| repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/") "https://github.com/#{repo_name}.git" end # Bundle edge Rails instead: gem 'rails', github: 'rails/rails' gem 'rails', '~> 6.1' # Use sqlite3 as the database for Active Record gem 'sqlite3' # Use Puma as the app server #gem 'puma', '~> 5.0' # Use SCSS for stylesheets gem 'sass-rails', '>= 6.0' # Transpile app-like JavaScript. Read more: https://github.com/rails/webpacker gem 'webpacker', '~> 5.0' # Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks gem 'turbolinks', '~> 5' # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder gem 'jbuilder', '~> 2.7' # Use Uglifier as compressor for JavaScript assets gem 'uglifier', '>= 1.3.0' # See https://github.com/rails/execjs#readme for more supported runtimes # gem 'therubyracer', platforms: :ruby # Use CoffeeScript for .coffee assets and views gem 'coffee-rails', '~> 4.2' # Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks #gem 'turbolinks', '~> 5' # Use Redis adapter to run Action Cable in production # gem 'redis', '~> 3.0' # Use ActiveModel has_secure_password # gem 'bcrypt', '~> 3.1.7' # Use Capistrano for deployment # gem 'capistrano-rails', group: :development gem "loofah", ">= 2.3.1" gem "rubyzip", ">= 1.3.0" group :development, :test do # Call 'byebug' anywhere in the code to stop execution and get a debugger console gem 'byebug', platforms: [:mri, :mingw, :x64_mingw] # Adds support for Capybara system testing and selenium driver gem 'capybara', '~> 2.13' gem 'selenium-webdriver' end group :development do # Access an interactive console on exception pages or by calling 'console' anywhere in the code. gem 'web-console', '>= 4.1.0' # Display performance information such as SQL time and flame graphs for each request in your browser. # Can be configured to work on production as well see: https://github.com/MiniProfiler/rack-mini-profiler/blob/master/README.md gem 'rack-mini-profiler', '~> 2.0' gem 'listen', '~> 3.3' # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring gem 'spring' end group :production do gem 'mysql2' end # Windows does not include zoneinfo files, so bundle the tzinfo-data gem gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby] gem 'blacklight', '~> 7.0' gem 'blacklight-spotlight', '3.5.0.1' group :development, :test do gem 'solr_wrapper', '>= 0.3' end gem 'spotlight-resources-dri', github: 'Digital-Repository-of-Ireland/spotlight-resources-dri', branch: 'main' gem 'rsolr', '>= 1.0', '< 3' gem 'bootstrap', '~> 4.0' gem 'bootstrap-sass' gem 'twitter-typeahead-rails', '0.11.1.pre.corejavascript' gem 'jquery-rails' gem 'devise' gem 'devise-guests', '~> 0.8' gem 'friendly_id' gem 'riiif' gem 'sitemap_generator' gem 'blacklight-gallery', '~> 4.0' gem 'openseadragon', '>= 0.2.0' gem 'blacklight-oembed', '~> 1.0' gem 'devise_invitable'
class Api::SchoolClassesController < ApplicationController before_action :authorized, only: [:create] def create school_class = SchoolClass.new(school_class_params) if school_class.save render json: { success: true, school_class: school_class } else render json: { success: false, error: school_class.errors.full_messages } end end private def school_class_params params .require(:school_class) .permit( :name, :user_id, :member_ids, user_school_classes_attributes: %w[id user_id school_id role _destroy] ) end end
## #* Product database model #* generated by scaffold class Product < ActiveRecord::Base attr_accessible :description, :image_url, :income, :manufacturer, :name, :price, :sold, :stock ## # the following relations are described in project.rdoc has_many :line_items has_many :orders, :through => :line_items ## # if there is a line_item which has the product in itself you cannot delete the product before_destroy :ensure_not_referenced_by_any_line_item def ensure_not_referenced_by_any_line_item if line_items.count.zero? return true else errors.add(:base, 'Line_items present') return false end end ## # validators for new product form validates :name , :description, :image_url, :manufacturer, :price, :stock, :presence => true validates_numericality_of :price, :greater_than_or_equal_to => 0 validates_numericality_of :stock, :greater_than_or_equal_to => 0 validates_uniqueness_of :name validates_format_of :image_url, :with => %r{\.(gif|png|jpg)$}i, :message => "Must be a url for an image in one of the following formats: GIF,JPG or PNG" default_scope :order => "updated_at" end
require 'rails_helper' RSpec.describe Message, type: :model do let!(:message) { create(:message, conversation: other_conversation, user: sender) } let(:other_conversation) { create(:conversation, sender: sender, receiver: receiver) } let(:receiver) { create(:user) } let(:sender) { create(:user) } it { belong_to :conversation } it { belong_to :user } it { is_expected.to validate_presence_of :body } it { is_expected.to validate_presence_of :conversation_id } it { is_expected.to validate_presence_of :user_id } context 'when time' do it 'show correct time' do expect(message.time).to eq message.created_at.strftime('%d/%m/%y at %l:%M %p') end end end
require "test_helper" describe User do subject { User } describe "db" do specify "columns & types" do must_have_column(:bio, :text) must_have_column(:confirmation_sent_at, :datetime) must_have_column(:confirmation_token) must_have_column(:confirmed_at, :datetime) must_have_column(:current_sign_in_at, :datetime) must_have_column(:current_sign_in_ip, :inet) must_have_column(:email) must_have_column(:encrypted_password) must_have_column(:last_sign_in_at, :datetime) must_have_column(:name) must_have_column(:given_name) must_have_column(:remember_created_at, :datetime) must_have_column(:reset_password_sent_at, :datetime) must_have_column(:reset_password_token) must_have_column(:sign_in_count, :integer) end specify "indexes" do must_have_index(:email) must_have_index(:name) must_have_index(:reset_password_token) end end specify "associations" do must_have_many(:ownerships) must_have_many(:orgs) must_have_many(:orgs_users) must_have_many(:vehicles) end describe "accepts_nested_attributes" do Given(:user_attrs) { FactoryGirl.attributes_for(:user) } Given(:vehicle) { FactoryGirl.create(:vehicle) } Given(:ownership_attrs) { FactoryGirl.attributes_for(:ownership ) } Given(:vehicle_attrs) { FactoryGirl.attributes_for(:vehicle)} describe "create user" do Given(:attrs) { user_attrs } Then { assert_difference("User.count") { User.create(attrs) } } end describe "create nested ownerships" do Given(:attrs) { user_attrs.merge(ownerships_attributes: [ ownership_attrs.merge(vehicle_id: vehicle.id)])} Then do assert_difference(["User.count", "Ownership.count"]) do user = User.create(attrs) end end end describe "create nested vehicle" do Given(:attrs) { user_attrs.merge( ownerships_attributes: [ ownership_attrs.merge( vehicle_attributes: FactoryGirl.attributes_for(:vehicle) ) ] ) } Then { assert_difference( [ "User.count", "Ownership.count", "Vehicle.count"]) { user = User.create(attrs) } } end end describe "names" do Given(:user) { FactoryGirl.build(:user) } describe ".temporary_name when localpart of the email" do describe "is all alphabet letters" do Given { user.update(email: "kiranhill@gmail.com") } Then { user.temporary_name.must_equal "Driver" } And { user.temporary_given_name.must_equal "Driver" } end describe "is split by a period" do Given { user.update(email: "kiran.hill@gmail.com") } Then { user.temporary_name.must_equal "Kiran Hill" } And { user.temporary_given_name.must_equal "Kiran" } end describe "is split by an underscore" do Given { user.update(email: "kiran_hill@gmail.com") } Then { user.temporary_name.must_equal "Kiran Hill" } And { user.temporary_given_name.must_equal "Kiran" } end describe "is split by single digit number" do Given { user.update(email: "kiran9hill@gmail.com") } Then { user.temporary_name.must_equal "Kiran Hill" } And { user.temporary_given_name.must_equal "Kiran" } end describe "has a multiple digit number" do Given { user.update(email: "kiran69hill@gmail.com") } Then { user.temporary_name.must_equal "Kiran Hill" } And { user.temporary_given_name.must_equal "Kiran" } end describe "is ended by a single digit number" do Given { user.update(email: "superman9@gmail.com") } Then { user.temporary_name.must_equal "Driver" } And { user.temporary_given_name.must_equal "Driver" } end end describe ".reconciled_name" do describe "when :name is nil but :given_name is set" do Given { user.update(email: "superman9@gmail.com", name: nil, given_name: "superman") } Then { user.reconciled_name.must_equal "superman" } And { user.reconciled_given_name.must_equal "superman" } end describe "when :name and :given_name are nil" do Given { user.update(email: "superman9@gmail.com", name: nil, given_name: nil) } Then { user.reconciled_name.must_equal "Driver" } And { user.reconciled_given_name.must_equal "Driver" } end describe "when :name is set but :given_name is nil" do Given { user.update(email: "superman9@gmail.com", name: "clark kent", given_name: nil) } Then { user.reconciled_name.must_equal "clark kent" } And { user.reconciled_given_name.must_equal "clark" } end describe "when :name and :given_name are set" do Given { user.update(email: "superman9@gmail.com", name: "clark kent", given_name: "superman") } Then { user.reconciled_name.must_equal "clark kent" } And { user.reconciled_given_name.must_equal "superman" } end end end end
class VshElasticsearch1 < Formula desc "Distributed search & analytics engine" homepage "https://www.elastic.co/products/elasticsearch" url "https://download.elastic.co/elasticsearch/elasticsearch/elasticsearch-1.7.6.tar.gz" sha256 "78affc30353730ec245dad1f17de242a4ad12cf808eaa87dd878e1ca10ed77df" license "Apache-2.0" revision 31 bottle do root_url "https://github.com/valet-sh/homebrew-core/releases/download/bottles" sha256 big_sur: "2960482590beaeefaf7c34952c00bdaed2e71480d86ea9b97c5ad3899d0b12c6" end depends_on "openjdk@8" def cluster_name "elasticsearch_#{ENV["USER"]}" end def install # Remove Windows files rm_f Dir["bin/*.bat"] rm_f Dir["bin/*.exe"] # Install everything else into package directory libexec.install "bin", "config", "lib" # Set up Elasticsearch for local development: inreplace "#{libexec}/config/elasticsearch.yml" do |s| # 1. Give the cluster a unique name s.gsub!(/#\s*cluster\.name: .*/, "cluster.name: #{cluster_name}") s.gsub!(/#\s*network\.host: .*/, "network.host: 127.0.0.1") s.gsub!(/#\s*http\.port: .*/, "http.port: 9201") # 2. Configure paths s.sub!(%r{#\s*path\.data: /path/to.+$}, "path.data: #{var}/lib/#{name}/") s.sub!(%r{#\s*path\.logs: /path/to.+$}, "path.logs: #{var}/log/#{name}/") end config_file = "#{libexec}/config/elasticsearch.yml" open(config_file, "a") { |f| f.puts "index.number_of_shards: 1\n" f.puts "index.number_of_replicas: 0\n" f.puts "index.store.throttle.type: none\n" f.puts "node.local: true\n" f.puts "script.inline: on\n" f.puts "script.indexed: on\n" } # Move config files into etc (etc/"#{name}").install Dir[libexec/"config/*"] (libexec/"config").rmtree inreplace libexec/"bin/plugin", "CDPATH=\"\"", "JAVA_HOME=\"#{Formula['openjdk@8'].opt_libexec}/openjdk.jdk/Contents/Home\"\nCDPATH=\"\"" inreplace libexec/"bin/elasticsearch", "CDPATH=\"\"", "JAVA_HOME=\"#{Formula['openjdk@8'].opt_libexec}/openjdk.jdk/Contents/Home\"\nCDPATH=\"\"" end def post_install # Make sure runtime directories exist (var/"lib/#{name}").mkpath (var/"log/#{name}").mkpath ln_s etc/"#{name}", libexec/"config" unless (libexec/"config").exist? (var/"#{name}/plugins").mkpath ln_s var/"#{name}/plugins", libexec/"plugins" unless (libexec/"plugins").exist? end def caveats <<~EOS Data: #{var}/lib/#{name}/ Logs: #{var}/log/#{name}/#{cluster_name}.log Plugins: #{var}/#{name}/plugins/ Config: #{etc}/#{name}/ EOS end service do run opt_libexec/"bin/elasticsearch" keep_alive false working_dir var log_path var/"log/elasticsearch.log" error_log_path var/"log/elasticsearch.log" end test do assert_includes(stable.url, "-oss-") port = free_port system "#{bin}/elasticsearch-plugin", "list" pid = testpath/"pid" begin system "#{bin}/elasticsearch", "-d", "-p", pid, "-Epath.data=#{testpath}/data", "-Ehttp.port=#{port}" sleep 10 system "curl", "-XGET", "localhost:#{port}/" ensure Process.kill(9, pid.read.to_i) end port = free_port (testpath/"config/elasticsearch.yml").write <<~EOS path.data: #{testpath}/data path.logs: #{testpath}/logs node.name: test-es-path-conf http.port: #{port} EOS cp etc/"elasticsearch/jvm.options", "config" cp etc/"elasticsearch/log4j2.properties", "config" ENV["ES_PATH_CONF"] = testpath/"config" pid = testpath/"pid" begin system "#{bin}/elasticsearch", "-d", "-p", pid sleep 10 system "curl", "-XGET", "localhost:#{port}/" output = shell_output("curl -s -XGET localhost:#{port}/_cat/nodes") assert_match "test-es-path-conf", output ensure Process.kill(9, pid.read.to_i) end end end
FactoryGirl.define do factory :repo, class: Twigg::Repo do ignore do path { GitSpecHelpers.scratch_repo } end initialize_with { new(path) } end end
class ResumesController < ApplicationController before_action :authenticate_user! before_action :set_resume, only: [:show, :edit, :update, :destroy] def index @resumes = Resume.where(user_id: current_user.id).order('updated_at DESC') end def show respond_to do |format| format.html format.pdf do render pdf: 'My Resume', disposition: 'attachment', template: 'resumes/show.pdf.haml', layout: 'pdf.html.erb' end end end def new @resume = Resume.new end def edit end def create sleep 1 @resume = Resume.new(resume_params) @resume.user_id = current_user.id @result = @resume.save if @result respond_to do |format| format.html { redirect_to edit_resume_path(@resume) } format.js { js_redirect_to edit_resume_path(@resume) } end else respond_to do |format| format.html format.js { flash.now[:error] = 'Mandatory information has not been filled in.' } end end end def update sleep 1 @result = @resume.update(resume_params) if @result respond_to do |format| format.html format.js { flash.now[:notice] = 'Resume was successfully updated.' } end else respond_to do |format| format.html format.js { flash.now[:error] = 'Mandatory information has not been filled in.' } end end end def destroy @resume.destroy redirect_to resumes_path end private def set_resume @resume = Resume.find(params[:id]) end def js_redirect_to(path) render js: %(window.location.href='#{path}') and return end def resume_params params.require(:resume).permit(:first_name, :last_name, :headline, :summary, :email, :phone, :address, :photo_url, :user_id, degrees_attributes: [ :id, :title, :school, :start_date, :end_date, :description, :_destroy ], positions_attributes: [ :id, :title, :company, :start_date, :end_date, :current, :description, :_destroy ] ) end end
class Product < ActiveRecord::Base validates_presence_of :nombre, :vigencia, :emision, :tipo, :saldo, :number belongs_to :user has_many :ope_pros has_many :operations, through: :ope_pros, dependent: :destroy end
module Lendable def lend @count -= 1 if count > 0 puts "You cannot lend this book any more" if count == 0 end end class Book include Lendable attr_reader :title, :author attr_writer :finished attr_accessor :count def initialize(title, author) @title = title @author = author @finished = false @count = 3 end def recommended_books [ Book.new("The Well-Grounded Rubyist", "David A. Black"), Book.new("Practical Object-Oriented Design in Ruby", "Sandi Metz"), Book.new("Effective Testing with RSpec 3", "Myron Marston") ] end end class AudioBook < Book def initialize(title, author) super(title, author) end def listen @finished = true end end class ComicBook < Book def initialize(title, author) super(title, author) end def read @finished = true end end
require 'spec_helper' describe Emarsys::Broadcast::TransactionalXmlBuilder do before(:each) do create_valid_config stub_senders_ok_two_senders end let(:config) { create_valid_config } let(:api) { Emarsys::Broadcast::API.new } let(:transactional_builder) { Emarsys::Broadcast::TransactionalXmlBuilder.new } let(:minimal_transaction) { create_minimal_transaction } let(:minimal_html_transaction) { create_minimal_html_transaction } describe 'initialize' do it 'should create a new instance of BatchXmlBuilder' do expect(transactional_builder).not_to be_nil end end describe '#build' do it 'should return a valid Emarsys Xml XML string' do actual_xml = transactional_builder.build(minimal_transaction).chomp fixture_path = File.dirname(__FILE__) + '/fixtures/xml/minimal_transaction.xml' expected_xml = File.read(fixture_path) expect(actual_xml).to eq expected_xml end it 'should properly escape the body of the Emarsys Xml XML string' do actual_xml = transactional_builder.build(minimal_html_transaction).chomp fixture_path = File.dirname(__FILE__) + '/fixtures/xml/minimal_escaped_transaction.xml' expected_xml = File.read(fixture_path) expect(actual_xml).to eq expected_xml end end end
class AccountTransferService attr_reader :token, :destiny_branch, :destiny_account_number, :amount def initialize(token:, destiny_branch:, destiny_account_number:, amount:) @token = token @destiny_branch = destiny_branch @destiny_account_number = destiny_account_number @amount = amount end def self.transfer(...) new(...).transfer end def transfer return if destiny_account.blank? return unless origin_balance_support_debit? return if destiny_limit_reached? create_transactions end private def origin_account @origin_account = User.find_by(token: token).account end def destiny_account @destiny_account = Account.find_by(branch: destiny_branch, account_number: destiny_account_number) end def transfer_amount @transfer_amount = amount.abs end def create_transactions ActiveRecord::Base.transaction do debit_transaction = AccountTransaction.create( account: origin_account, amount: -transfer_amount, transaction_type: 'transfer' ) update_balance(origin_account, -transfer_amount) credit_transaction = AccountTransaction.create( account: destiny_account, amount: transfer_amount, transaction_type: 'transfer' ) update_balance(destiny_account, transfer_amount) [debit_transaction, credit_transaction] end end def update_balance(account, value) balance = account.balance account.update!(balance: balance + value) end def origin_balance_support_debit? origin_account.balance - transfer_amount >= 0 end def destiny_limit_reached? destiny_account.balance + transfer_amount > destiny_account.limit end end
require 'test/unit' class Numeric @@currencies = {'yen' => 0.013, 'euro' => 1.292, 'rupee' => 0.019, 'dollar' => 1.0} def convert_to(currency, divide=false) singular_currency = currency.to_s.gsub( /s$/, '') if @@currencies.has_key?(singular_currency) if divide return self / @@currencies[singular_currency] else return self * @@currencies[singular_currency] end end end def method_missing(method_id) convert_to(method_id) or super end def in(currency) convert_to(currency, divide=true) end end def _palindrome?(string) # determines whether a given word or phrase is a palindrome cleaned = string.gsub(/\W/, '').downcase cleaned == cleaned.reverse end class String; def palindrome?; _palindrome?(self) end; end module Enumerable def palindrome? self.to_a == self.to_a.reverse end end class Hash def palindrome? false end end class VPT include Enumerable @@l = [1,2,3,2,1] def each @@l.each {|x| yield x} end end class HW2Test < Test::Unit::TestCase def test_a assert 2.rupee.in(:dollar).between?(0.037, 0.039) assert 3.yen.in(:dollar).between?(0.038, 0.040) assert 6.euro.in(:dollar).between?(7.75, 7.76) assert 2.rupees.in(:dollars).between?(0.037, 0.039) assert 3.yen.in(:dollars).between?(0.038, 0.040) assert 6.euros.in(:dollars).between?(7.75, 7.76) assert 5.rupees.in(:yen).between?(7.2, 7.4) end def test_b assert "A man, a plan, a canal -- Panama".palindrome? assert "a man a plan a canal panama".palindrome? end def test_c assert [1,2,3,2,1].palindrome? assert ["a", "b", "c", "b", "a"].palindrome? assert ![1,2,3,4,3,2].palindrome? assert !Hash.new.palindrome? # well, [] == [], i just leave it this way assert !{"hello"=> "world"}.palindrome? assert !(1..2).palindrome? assert ![12,21].palindrome? pvalue = Hash.new.palindrome? assert pvalue.is_a?(TrueClass) || pvalue.is_a?(FalseClass) assert VPT.new.palindrome? end end
class MessagesController < ApplicationController def new @message = Message.new() end def create @message = Message.new(message_params) if @message.save redirect_to root_url else render json: @messages.erorrs.full_messages end end private def message_params params.require(:message).permit(:message) end end
require_relative '../../helpers' CONFIRM_ORDER = 'confirm' CONFIRM_ORDER_URL = url(CLIENT_ORDER, CONFIRM_ORDER) WebMock::Stub.request( url: CONFIRM_ORDER_URL, request_body: %( { "method": "#{CONFIRM_ORDER}", "appid": "(.*)", "uid": "(.*)", "orderId": "(.*)" }) ) do |request| params = JSON.parse(request.body) order_id = params['orderId'] begin status_code = 200 @uid = "3440fb81-9b10-4095-9886-022d751c162a" product_id = DebitCardDataKeeper.find(order_id) # В случае, если подтверждается заявка на открытие карты confirm_client_order_error if product_id == '4077218911' confirm_order_not_found_error if product_id == '4077213541' body = { uid: @uid, ErrCode: '0', ErrText: '', status: "PROCESSING" } rescue ConfirmClientOrderErrors => e body = e.error_body end { status: status_code, headers: {'Content-Type' => 'application/json'}, body: body.to_json } end class ConfirmClientOrderErrors < StandardError attr_accessor :error_body def initialize(message, object) super(message) self.error_body = object end end def confirm_client_order_error code = '1' message = 'Ошибка при подтверждении заявки' confirm_client_order_error(code, message) end def confirm_order_not_found_error code = '2115' message = 'Заявка на открытие продукта не найдена' confirm_client_order_error(code, message) end def confirm_client_order_error(code, message) raise ConfirmClientOrderErrors.new(nil, confirm_client_order_error_body(code, message)) end def confirm_client_order_error_body(code, message) { uid: @uid, ErrCode: code, ErrText: "АБС: ORA-20300: APP-TNG_ESB_INT.TNG_ESB_CLIENT_ORDERS: #{message}" } end
require 'spec_helper' describe Education do it "is valid with all required attributes by validations" do expect(build(:education)).to be_valid end it "should not pass if degree_id is missing" do expect(build(:education, degree_id: nil)).to have(1).errors_on(:degree_id) end it "should not pass if speciality is missing" do expect(build(:education, speciality: nil)).to have(1).errors_on(:speciality) end it "should not pass if institution is missing" do expect(build(:education, institution: nil)).to have(1).errors_on(:institution) end end
# frozen_string_literal: true # typed: false require 'spec_helper' describe AlphaCard::Capture do context 'with invalid attributes' do let(:capture) { AlphaCard::Capture.new(transaction_id: 'Some ID', amount: '10.05') } let(:response) { capture.process } it 'response with error' do expect(response.error?).to be_truthy expect(response.message).to eq('Transaction was rejected by gateway') end end context 'with valid attributes' do let(:capture) { AlphaCard::Capture.new(transaction_id: 'Some ID', amount: '10.05', order_id: '1', shipping_carrier: '2') } let(:order) { AlphaCard::Order.new(id: '1', description: 'Test') } let(:card_exp) { (Time.now + 31_104_000).strftime('%m%y') } let(:auth) { AlphaCard::Auth.new(card_expiration_date: card_exp, card_number: '4111111111111111', amount: '5.00') } it 'has valid request params' do expected_params = { transactionid: 'Some ID', type: 'capture', amount: '10.05', shipping_carrier: '2', orderid: '1', } expect(capture.attributes_for_request).to eq(expected_params) end it 'processed successfully' do response = auth.create(order) expect(response.success?).to be_truthy expect(response.transaction_id).not_to be_nil response = AlphaCard::Capture.new(transaction_id: response.transaction_id, amount: '2.00').create expect(response.success?).to be_truthy expect(response.text).to eq('SUCCESS') end end context 'with blank attributes' do it 'raises an InvalidObject error' do expect { AlphaCard::Refund.new.process }.to raise_error(AlphaCard::ValidationError) expect { AlphaCard::Refund.new(amount: '1.05').process }.to raise_error(AlphaCard::ValidationError) end end end
# frozen_string_literal: true module Vgmdb class Api ENDPOINT_URI = 'https://vgmdb.net/db/calendar.php' public_constant :ENDPOINT_URI def parse(url) body = ::Vgmdb::Client.new.get(url) ::Nokogiri::HTML.parse(body) end def get_url(time) doc = parse("#{::Vgmdb::Api::ENDPOINT_URI}?year=#{time.year}&month=#{time.month}") urls = doc.xpath("//*[@id=\"#{time.strftime('%Y%m%d')}\"]/following-sibling::div[1]/div/div/div/a").map do |n| n.attributes['href'].value rescue ::StandardError nil end urls.compact end def get_id(url) attributes = parse(url).xpath("//a[contains(@href,'music.apple.com')]").first&.attributes attributes['href']&.value&.slice(/([0-9]+)$/) if attributes end def get_ids(time) # @type var results: ::Array[::String] results = [] get_url(time).each do |url| id = get_id(url) results << id if id end results end end end
require 'rails_helper' RSpec.describe Comment, type: :model do subject(:comment) { build(:comment) } it 'has a valid factory' do expect(comment).to be_valid end it 'requires content' do comment.content = '' expect(comment).not_to be_valid expect(comment.errors_on(:content)).to include("can't be blank") end end
require_relative "operacao" class Conta attr_accessor :lista def initialize(lista,numero,saldo) @lista = lista @numero = numero @saldo = saldo end def numero @numero end def saldo @saldo end def transacao(valor) operacao = Operacao.new(@saldo,valor) @saldo = operacao.novo_saldo set_novo_saldo end def print_saldo puts "#{numero},#{saldo}" end private def set_novo_saldo @lista.each { |conta| conta[1] = saldo if conta[0] == numero } end end
require "spec_helper" require "rails_helper" describe ApiConnect do it "Usuário não cadastrado (julianalucena). Após a chamada para a API do GitHub o usuário e repositorios devem ser salvos." do User.destroy_all Repository.destroy_all get "/julianalucena" expect(response).to be_success expect(User.all.count).to eq(1) expect(Repository.all.count).to be > 1 end it 'Usuário cadastrado a partir da APi do github deve ser disponibilizado via api pela aplicação.' do User.destroy_all Repository.destroy_all get "/julianalucena" get '/api/v1/julianalucena', nil, { 'api-key' => "15ae2edf99da63f614bf621cb4321eb7"} json = JSON.parse(response.body) expect(json['login']).to eq('julianalucena') expect(response).to be_success end it 'Repositórios cadastrado a partir da APi do github devem ser disponibilizados via api pela aplicação.' do User.destroy_all Repository.destroy_all get "/julianalucena" get '/api/v1/repositories/julianalucena', nil, { 'api-key' => "15ae2edf99da63f614bf621cb4321eb7"} json = JSON.parse(response.body) user = User.first expect(response).to be_success expect(json[0]['user_id']).to eq(user.id) end end
Given(/^a project "(.*?)" exists$/) do |project_name| step %{I run `profess new project #{project_name}`} end When(/^I change to the root of the project "(.*?)"$/) do |project_name| step %{I cd to "#{project_name}"} end
module AppHelper require './locator.rb' require './dice_scraper.rb' # Locator pulls ZIP code based on client IP def session_location(client_ip) if session[:zip].nil? location = get_location(client_ip) save(location) else location = load_location end location end # Scraper pulls job postings directly from Dice.com def run_search(location) scraper = DiceScraper.new if params.nil? results = scraper.search(location) else results = scraper.search_with_params(params, location) end results end private def get_location(client_ip) locator = Locator.new(client_ip) locator.fetch_location end def save(location) session[:zip] = location end def load_location session[:zip] end end
# frozen_string_literal: true class Admin::Api::ObjectsController < Admin::Api::BaseController clear_respond_to respond_to :json ALLOWED_OBJECTS = %w[service account proxy backend_api].freeze before_action :authorize! ##~ e = sapi.apis.add ##~ e.path = "/admin/api/objects/status.json" # ##~ op = e.operations.add ##~ op.httpMethod = "GET" ##~ op.summary = "Object deletion status for objects that are deleted asynchronously" ##~ op.description = "Returns an object status. (200/404). Useful for those objects that deleted asynchronously in order to know if the deletion has been completed(404) or not(200)" ##~ op.group = "objects" # ##~ op.parameters.add @parameter_access_token ##~ op.parameters.add :dataType => "string", :required => true, :paramType => "query", :name => "object_type", :description => "Object type has to be service, account, proxy or backend_api." ##~ op.parameters.add :dataType => "string", :required => true, :paramType => "query", :name => "object_id", :description => "Object ID." def status status_object = status_object_type.classify.constantize.unscoped.find(status_object_id) authorize_tenant!(status_object) head(:ok) end private def status_object_type @status_object_type ||= params.fetch(:object_type).to_s end def status_object_id @status_object_id ||= params.fetch(:object_id) end def authorize_tenant!(status_object) raise_access_denied if !current_account.master? && current_account.tenant_id != status_object.tenant_id end def authorize! raise_access_denied if unknown_status_object || current_user_not_admin end def unknown_status_object ALLOWED_OBJECTS.exclude?(status_object_type) end def current_user_not_admin !current_user&.admin? end def raise_access_denied raise CanCan::AccessDenied end end
# coding: utf-8 module Zenithal::ZenithalParserMethod ELEMENT_START = "\\" MACRO_START = "&" ESCAPE_START = "`" ATTRIBUTE_START = "|" ATTRIBUTE_END = "|" ATTRIBUTE_EQUAL = "=" ATTRIBUTE_SEPARATOR = "," STRING_START = "\"" STRING_END = "\"" CONTENT_START = "<" CONTENT_END = ">" CONTENT_DELIMITER = ";" SPECIAL_ELEMENT_STARTS = {:brace => "{", :bracket => "[", :slash => "/"} SPECIAL_ELEMENT_ENDS = {:brace => "}", :bracket => "]", :slash => "/"} COMMENT_DELIMITER = "#" SYSTEM_INSTRUCTION_NAME = "zml" MARK_CHARS = {:instruction => "?", :trim => "*", :verbal => "~", :multiple => "+"} ESCAPE_CHARS = ["&", "<", ">", "'", "\"", "{", "}", "[", "]", "/", "\\", "|", "`", "#", ";"] SPACE_CHARS = [0x20, 0x9, 0xD, 0xA] VALID_FIRST_IDENTIFIER_CHARS = [ 0x3A, 0x5F, 0x41..0x5A, 0x61..0x7A, 0xC0..0xD6, 0xD8..0xF6, 0xF8..0x2FF, 0x370..0x37D, 0x37F..0x1FFF, 0x200C..0x200D, 0x2070..0x218F, 0x2C00..0x2FEF, 0x3001..0xD7FF, 0xF900..0xFDCF, 0xFDF0..0xFFFD, 0x10000..0xEFFFF ] VALID_MIDDLE_IDENTIFIER_CHARS = [ 0x2D, 0x2E, 0x3A, 0x5F, 0xB7, 0x30..0x39, 0x41..0x5A, 0x61..0x7A, 0xC0..0xD6, 0xD8..0xF6, 0xF8..0x2FF, 0x300..0x36F, 0x370..0x37D, 0x37F..0x1FFF, 0x200C..0x200D, 0x2070..0x218F, 0x2C00..0x2FEF, 0x203F..0x2040, 0x3001..0xD7FF, 0xF900..0xFDCF, 0xFDF0..0xFFFD, 0x10000..0xEFFFF ] private def parse if @whole parse_document else parse_nodes({}) end end def parse_document document = REXML::Document.new check_version children = parse_nodes({}) if @exact parse_eof end children.each do |child| document.add(child) end return document end def parse_nodes(options) nodes = nil if options[:plugin] nodes = options[:plugin].send(:parse) elsif options[:verbal] raw_nodes = many(->{parse_text(options)}) nodes = raw_nodes.inject(REXML::Nodes[], :<<) else parsers = [] parsers << ->{parse_element(options)} if options[:in_slash] next_options = options.clone next_options.delete(:in_slash) else next_options = options end @special_element_names.each do |kind, name| unless kind == :slash && options[:in_slash] parsers << ->{parse_special_element(kind, next_options)} end end parsers << ->{parse_comment(options)} parsers << ->{parse_text(options)} raw_nodes = many(->{choose(*parsers)}) nodes = raw_nodes.inject(REXML::Nodes[], :<<) end return nodes end def parse_element(options) name, marks, attributes, macro = parse_tag(options) next_options = determine_options(name, marks, attributes, macro, options) children_list = parse_children_list(next_options) if name == SYSTEM_INSTRUCTION_NAME parse_space end if macro element = process_macro(name, marks, attributes, children_list, options) else element = create_element(name, marks, attributes, children_list, options) end return element end def parse_special_element(kind, options) parse_char(SPECIAL_ELEMENT_STARTS[kind]) if kind == :slash next_options = options.clone next_options[:in_slash] = true else next_options = options end children = parse_nodes(next_options) parse_char(SPECIAL_ELEMENT_ENDS[kind]) element = create_special_element(kind, children, options) return element end def parse_tag(options) start_char = parse_char_any([ELEMENT_START, MACRO_START]) name = parse_identifier(options) marks = parse_marks(options) attributes = maybe(->{parse_attributes(options)}) || {} macro = start_char == MACRO_START return name, marks, attributes, macro end def parse_marks(options) marks = many(->{parse_mark(options)}) return marks end def parse_mark(options) parsers = MARK_CHARS.map do |mark, query| next ->{parse_char(query).yield_self{|_| mark}} end mark = choose(*parsers) return mark end def parse_attributes(options) parse_char(ATTRIBUTE_START) first_attribute = parse_attribute(true, options) rest_attribtues = many(->{parse_attribute(false, options)}) attributes = first_attribute.merge(*rest_attribtues) parse_char(ATTRIBUTE_END) return attributes end def parse_attribute(first, options) unless first parse_char(ATTRIBUTE_SEPARATOR) end parse_space name = parse_identifier(options) parse_space value = maybe(->{parse_attribute_value(options)}) || name parse_space attribute = {name => value} return attribute end def parse_attribute_value(options) parse_char(ATTRIBUTE_EQUAL) parse_space value = parse_string(options) return value end def parse_string(options) parse_char(STRING_START) strings = many(->{parse_string_plain_or_escape(options)}) parse_char(STRING_END) string = strings.join return string end def parse_string_plain(options) chars = many(->{parse_char_out([STRING_END, ESCAPE_START])}, 1..) string = chars.join return string end def parse_string_plain_or_escape(options) string = choose(->{parse_escape(:string, options)}, ->{parse_string_plain(options)}) return string end def parse_children_list(options) if @version == "1.0" children_list = parse_children_chain(options) else children_list = choose(->{parse_empty_children_chain(options)}, ->{parse_children_chain(options)}) end return children_list end def parse_children_chain(options) if @version == "1.0" first_children = choose(->{parse_empty_children(options)}, ->{parse_children(options)}) rest_children_list = many(->{parse_children(options)}) children_list = [first_children] + rest_children_list else children_list = many(->{parse_children(options)}, 1..) end return children_list end def parse_empty_children_chain(options) children = parse_empty_children(options) children_list = [children] return children_list end def parse_children(options) parse_char(CONTENT_START) children = parse_nodes(options) parse_char(CONTENT_END) return children end def parse_empty_children(options) if @version == "1.0" parse_char(CONTENT_END) children = REXML::Nodes[] else parse_char(CONTENT_DELIMITER) children = REXML::Nodes[] end return children end def parse_text(options) raw_texts = many(->{parse_text_plain_or_escape(options)}, 1..) text = create_text(raw_texts.join, options) return text end def parse_text_plain(options) out_chars = [ESCAPE_START, CONTENT_END] unless options[:verbal] out_chars.push(ELEMENT_START, MACRO_START, CONTENT_START, COMMENT_DELIMITER) if @version == "1.1" out_chars.push(CONTENT_DELIMITER) end @special_element_names.each do |kind, name| out_chars.push(SPECIAL_ELEMENT_STARTS[kind], SPECIAL_ELEMENT_ENDS[kind]) end end chars = many(->{parse_char_out(out_chars)}, 1..) string = chars.join return string end def parse_text_plain_or_escape(options) string = choose(->{parse_escape(:text, options)}, ->{parse_text_plain(options)}) return string end def parse_comment(options) parse_char(COMMENT_DELIMITER) comment = choose(->{parse_line_comment(options)}, ->{parse_block_comment(options)}) return comment end def parse_line_comment(options) parse_char(COMMENT_DELIMITER) content = parse_line_comment_content(options) parse_char("\n") comment = create_comment(:line, content, options) return comment end def parse_line_comment_content(options) chars = many(->{parse_char_out(["\n"])}) content = chars.join return content end def parse_block_comment(options) parse_char(CONTENT_START) content = parse_block_comment_content(options) parse_char(CONTENT_END) if @version == "1.0" parse_char(COMMENT_DELIMITER) end comment = create_comment(:block, content, options) return comment end def parse_block_comment_content(options) chars = many(->{parse_char_out([CONTENT_END])}) content = chars.join return content end def parse_escape(place, options) parse_char(ESCAPE_START) char = parse_char escape = create_escape(place, char, options) return escape end def parse_identifier(options) first_char = parse_first_identifier_char(options) rest_chars = many(->{parse_middle_identifier_char(options)}) identifier = first_char + rest_chars.join return identifier end def parse_first_identifier_char(options) char = parse_char_any(VALID_FIRST_IDENTIFIER_CHARS) return char end def parse_middle_identifier_char(options) char = parse_char_any(VALID_MIDDLE_IDENTIFIER_CHARS) return char end def parse_space space = many(->{parse_char_any(SPACE_CHARS)}) return space end def determine_options(name, marks, attributes, macro, options) if marks.include?(:verbal) options = options.clone options[:verbal] = true end if macro && @plugins.key?(name) options = options.clone options[:plugin] = @plugins[name].call(attributes) end return options end def create_element(name, marks, attributes, children_list, options) nodes = REXML::Nodes[] if marks.include?(:trim) children_list.each do |children| children.trim_indents end end if marks.include?(:instruction) unless children_list.size <= 1 throw_custom("Processing instruction cannot have more than one argument") end nodes = create_instruction(name, attributes, children_list.first, options) else unless marks.include?(:multiple) || children_list.size <= 1 throw_custom("Normal element cannot have more than one argument") end nodes = create_normal_element(name, attributes, children_list, options) end return nodes end def create_instruction(target, attributes, children, options) nodes = REXML::Nodes[] if target == SYSTEM_INSTRUCTION_NAME @version = attributes["version"] if attributes["version"] @special_element_names[:brace] = attributes["brace"] if attributes["brace"] @special_element_names[:bracket] = attributes["bracket"] if attributes["bracket"] @special_element_names[:slash] = attributes["slash"] if attributes["slash"] elsif target == "xml" instruction = REXML::XMLDecl.new instruction.version = attributes["version"] || REXML::XMLDecl::DEFAULT_VERSION instruction.encoding = attributes["encoding"] instruction.standalone = attributes["standalone"] nodes << instruction else instruction = REXML::Instruction.new(target) actual_contents = [] attributes.each do |key, value| actual_contents << "#{key}=\"#{value}\"" end if children.first && !children.first.empty? actual_contents << children.first end instruction.content = actual_contents.join(" ") nodes << instruction end return nodes end def create_normal_element(name, attributes, children_list, options) nodes = REXML::Nodes[] children_list.each do |children| element = REXML::Element.new(name) attributes.each do |key, value| element.add_attribute(key, value) end children.each do |child| element.add(child) end nodes << element end return nodes end def create_special_element(kind, children, options) name = @special_element_names[kind] if name nodes = create_element(name, [], {}, [children], options) else throw_custom("No name specified for #{kind} elements") end return nodes end def create_text(raw_text, options) text = REXML::Text.new(raw_text, true, nil, false) return text end def create_comment(kind, content, options) comment = REXML::Comment.new(" " + content.strip + " ") return comment end def create_escape(place, char, options) unless ESCAPE_CHARS.include?(char) throw_custom("Invalid escape") end return char end def process_macro(name, marks, attributes, children_list, options) elements = REXML::Nodes[] if @macros.key?(name) raw_elements = @macros[name].call(attributes, children_list) raw_elements.each do |raw_element| elements << raw_element end elsif @plugins.key?(name) elements = children_list.first else throw_custom("No such macro '#{name}'") end return elements end def check_version string = @source.string if match = string.match(/\\zml\?\s*\|.*version\s*=\s*"(\d+\.\d+)".*\|/) @version = match[1] end end end class Zenithal::ZenithalParser < Zenithal::Parser include Zenithal::ZenithalParserMethod attr_accessor :exact attr_accessor :whole def initialize(source) super(source) @exact = true @whole = true @fallback_version = "1.0" @version = "1.0" @fallback_special_element_names = {:brace => nil, :bracket => nil, :slash => nil} @special_element_names = {:brace => nil, :bracket => nil, :slash => nil} @macros = {} @plugins = {} end def update(source) super(source) @version = @fallback_version @special_element_names = @fallback_special_element_names end # Registers a macro. # To the argument block will be passed two arguments: the first is a hash of the attributes, the second is a list of the children nodes. def register_macro(name, &block) @macros.store(name, block) end def unregister_macro(name) @macros.delete(name) end # Registers a plugin, which enables us to apply another parser in certain macros. # If a class instance is passed, simply an instance of that class will be created and used as a custom parser. # If a block is passed, it will be called to create a custom parser. # To this block will be passed one argument: the attributes which are specified to the macro. def register_plugin(name, clazz = nil, &block) if clazz block = lambda{|_| clazz.new(@source)} end @plugins.store(name, block) end def unregister_plugin(name) @plugins.delete(name) end def version=(version) @version = version @fallback_version = version end def brace_name=(name) @fallback_special_element_names[:brace] = name @special_element_names[:brace] = name end def bracket_name=(name) @fallback_special_element_names[:bracket] = name @special_element_names[:bracket] = name end def slash_name=(name) @fallback_special_element_names[:slash] = name @special_element_names[:slash] = name end end
module VimBrain module Vim module UserDialog include Command def inputlist(leadingtext,options) args = [] options.each_index { |i| args[i] = "#{i + 1}. " + options[i] } args = args.unshift(leadingtext).to_vim_list vim_evaluate("inputlist(#{args})").to_i end def input(message,default) rv = vim_evaluate("input('#{message} ','#{default}')") # Remove the message from the command line: print "" rv end def confirm(message) nl = "\n" vim_evaluate("confirm('#{message}', '&Yes#{nl}&No')") == '1' end end end class UserDialog include Vim::UserDialog end end
# coding: utf-8 require 'spec_helper' feature "Simple search", %q{ As an guest I should be able to search books } do background do create(:admin) end scenario "simple title search" do ['Primeiro', 'Segundo'].each do |title| create(:book, :title => title) end visit books_path fill_in "search", :with => 'Prim' submit_form('simple_search') page.should have_content('Primeiro') page.should_not have_content('Segundo') end scenario "simple title search in user page" do user = create(:user) ['Primeiro', 'Segundo'].each do |title| create(:book, :title => title, :user => user) end visit user_books_path(user) fill_in "search", :with => 'Prim' submit_form('simple_search') page.should have_content('Primeiro') visit user_books_path(create(:user)) fill_in "search", :with => 'Prim' submit_form('simple_search') page.should_not have_content('Primeiro') end scenario "simple search various attributes" do create(:book, :title => 'With Title') create(:book, :authors => [create(:author, :name =>'With Author')]) create(:book, :title => 'Tag', :tags => [create(:tag, :title => 'With')]) create(:book, :title => 'No Title') create(:book, :authors => [create(:author, :name =>'No Author')]) create(:book, :tags => [create(:tag, :title => 'No Tag')]) visit books_path fill_in "search", :with => 'With' submit_form('simple_search') page.should have_content('With Title') page.should have_content('Tag') page.should have_content('With Author') page.should_not have_content('No Title') page.should_not have_content('No Tag') page.should_not have_content('No Author') end scenario "Accent search" do ['Primeiro', 'Prímeirô', 'Segundo'].each do |title| create(:book, :title => title) end visit books_path fill_in "search", :with => 'Prim' submit_form('simple_search') page.should have_content('Primeiro') page.should have_content('Prímeirô') page.should_not have_content('Segundo') end end feature "Advanced search", %q{ As an guest I should be able to make advanced searches } do background do create(:admin) end scenario "PDF filter" do create(:book, :title => "No PDF", :pdflink => '') create(:book, :title => "With PDF", :pdflink => "http://www.example.com") visit books_path check "pdf_filter" click_button "Busca" page.should have_content "With PDF" page.should_not have_content "No PDF" end scenario "Language filter" do create(:book, :title => "English", :language => 'en') create(:book, :title => "Portuguese", :language => 'pt') visit books_path select "en", :from => 'language_filter[]' click_button "Busca" page.should have_content "English" page.should_not have_content "Portuguese" end scenario "Author filter" do create(:book, :title => 'Title', :authors => [create(:author, :name => 'First')]) create(:book, :title => 'First', :authors => [create(:author, :name => 'Second')]) visit books_path fill_in 'author_filter', :with => 'First' click_button "Busca" page.should have_content "Title" page.should_not have_content "Second" end scenario "Title filter" do create(:book, :title => 'First', :authors => [create(:author, :name => 'Author')]) create(:book, :title => 'Second', :authors => [create(:author, :name => 'First')]) visit books_path fill_in 'title_filter', :with => 'First' click_button "Busca" page.should have_content "First" page.should_not have_content "Second" end scenario "Editor filter" do create(:book, :title => 'Title', :editor => 'First') create(:book, :title => 'First', :editor => 'Second') visit books_path fill_in 'editor_filter', :with => 'First' click_button "Busca" page.should have_content "Title" page.should_not have_content "First" end scenario "Search with filter" do create(:book, :title => 'First', :authors => [create(:author, :name => 'Author')]) create(:book, :title => 'Second', :authors => [create(:author, :name => 'First')]) create(:book, :title => 'Third', :authors => [create(:author, :name => 'Author')]) visit books_path fill_in "search", :with => 'First' submit_form('simple_search') page.should have_content 'First' page.should have_content 'Second' page.should_not have_content 'Third' fill_in 'author_filter', :with => 'Author' click_button "Busca" page.should have_content 'First' page.should_not have_content 'Second' page.should_not have_content 'Third' end scenario "Filter Library" do users = [create(:user), create(:user)] books = [create(:book, :title => 'First', :user => users[0]), create(:book, :title => 'Second', :user => users[1])] visit books_path select users[0].name, :from => 'user_filter[]' click_button "Busca" page.should have_content books[0].title page.should_not have_content books[1].title end end
class AddEventDateToIncident < ActiveRecord::Migration def change add_column :incidents, :event_date, :date end end
module Wotan class App < Nesta::App def current_breadcrumb_class 'current' end end end Tilt.prefer Tilt::KramdownTemplate
# creando getters para comprobar la prueba require 'gcd' class Racional attr_reader :num, :denom def initialize (num,denom) # se llama al maximo comun divisor para reducir la funcion dividiendo entre ese numero reducir = gcd(num, denom) @num = num/reducir @denom = denom/reducir end def to_s "#{num}/#{denom}" end # se utiliza para mostrar en formato flotante def to_f num.to_f/denom end end
class Automobiles def Operation raise NotImplemented Error, 'Operation() must be defined in subclass' end end class Car < Automobiles def Operation puts "Car::Operation()" end end class BasicCar < Automobiles def initialize(obj) @comp = obj end def Operation puts "BasicCar::Operation()" @comp.Operation end end class SportsCar < BasicCar def initialize(obj) super(obj) @addedFeature = nil end def Operation super @addedFeature = 1 puts "SportsCar::Operation()" puts "SportsCar::addedFeature = #{@addedFeature}" end end class LuxuryCar < BasicCar def initialize(obj) super(obj) end def Operation super puts "LuxuryCar::Operation()" self.AddedBehavior end def AddedBehavior puts "LuxuryCar::AddedBehavior()" end end myCar = SportsCar.new(LuxuryCar.new(Car.new)) myCar.Operation
Facter.add("domain_role") do confine :kernel => :windows setcode do standalone_server = Facter::Util::Resolution.exec('C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe -Command ($Env:Computername -eq $Env:Userdomain)') if standalone_server == 'True' 'standalone_server' else domain_controller = Facter::Util::Resolution.exec('C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe -Command (Get-ADDomainController -EA SilentlyContinue).Enabled') if domain_controller 'domain_controller' else 'member_server' end end end end
class EmailForm < ApplicationRecord validates_presence_of :description, :contents end
require 'spec_helper' describe User do describe "association" do it "must belong to an organization" do user = FactoryGirl.build(:user, :organization => nil) user.should_not be_valid user.organization = FactoryGirl.create :organization user.should be_valid end end describe "#from_organization?" do let(:user) { FactoryGirl.create(:user) } it "returns true if user belongs to organization" do user.from_organization?(user.organization).should be_true end it "returns false if user DOESN'T belong to organization" do other_organization = FactoryGirl.create(:organization) user.from_organization?(other_organization).should be_false end end end
module Registration::Cell class Edit < Abroaders::Cell::Base include Abroaders::LogoHelper option :form def title 'Email & Password Settings' end private def errors cell(Abroaders::Cell::ValidationErrorsAlert, form) end def form_tag(&block) form_for form, as: :account, url: account_path, html: { role: 'form' }, &block end def submit_btn(f) f.submit 'Save Account Settings', class: 'btn btn-primary btn-lg' end end end
require './app.rb' describe App do let(:app) { App.new } context "GET homepage" do let(:response) { get "/" } it "return status 200" do expect(response.status).to eq 200 end end end
module AddressValidate module Configuration API_URLS = { test: 'http://production.shippingapis.com/ShippingAPITest.dll', production: 'http://production.shippingapis.com/ShippingAPI.dll' } attr_accessor :environment, :username, :password, :firm_name, :street_address, :apartment_number, :city, :state, :zip_5, :zip_4 def configure yield self end def self.extended(base) base.set_default_configuration end def verify_url API_URLS[environment] end def set_default_configuration self.environment = :production self.firm_name = :firm_name self.street_address = :street_address self.apartment_number = :apartment_number self.city = :city self.state = :state self.zip_5 = :zip_5 self.zip_4 = :zip_4 end end end
class Artist < ApplicationRecord has_many :murals has_many :neighborhoods, through: :murals validates :name, presence: true validates :artist_name, presence: true validates :bio, presence: true def self.all_artists self.all.order(artist_name: :asc) end def self.most_popular joins(:murals).group(:artist_id).order('count(murals.artist_id)desc').limit(5) end def self.next(artist) self.where("id > ?", artist.id).first end def self.previous(artist) self.where("id < ?", artist.id).first end def find_next_artist artist = Artist.where("id > ?", id).first artist ? artist : Artist.first end def find_previous_artist artist = Artist.where("id < ?", id).last artist ? artist : Artist.last end end
class AddXblToProfiles < ActiveRecord::Migration def change add_column :profiles, :XBL, :integer add_column :profiles, :Gamertag, :string add_column :profiles, :XBLDescription, :string add_column :profiles, :XBone, :Boolean add_column :profiles, :X360, :Boolean end end
require_relative 'mongodb_driver' require_relative 'updatable_config' require 'digest/md5' module VCAP::MongodbController class MongoProvisioner PROVISION_CHANNEL = "mongodb.provision".freeze attr_reader :config, :message_bus, :driver, :provision_config, :nodes def initialize(config, message_bus, node_config, driver) @config = config @message_bus = message_bus @driver = driver @provision_config = UpdatableConfig.new(config[:provision_config]) node_config.add_observer(self, :node_config_changed) if config.master_node? end def logger @logger ||= Steno.logger("mc.provisioner") end def run if config.master_node? attach_as_master end end def node_config_changed(c) @nodes = c[:nodes] end private def attach_as_master logger.info "Attaching as master" message_bus.subscribe(PROVISION_CHANNEL) do |msg, reply| process_provision_message(msg, reply) end driver.start end def process_provision_message(msg, reply) logger.info "Processing message", msg r = MongoCommand.new case msg["command"] when "provision" then provision(r, msg["data"]) when "unprovision" then unprovision(r, msg["data"]) when "bind" then bind(r, msg["data"]) when "unbind" then unbind(r, msg["data"]) else message_bus.publish(reply, {error: true, message: "Unknown command #{e}"}) end r.callback {|d| message_bus.publish(reply, {error: false, data: d}) }. errback do |e| logger.warn(e[:message], e) message_bus.publish(reply, {error: true, data: e}) end rescue e logger.warn(e[:message], e) message_bus.publish(reply, {error: true, data: e}) end # Provision database for controller # Data is a hash with items: # * id is provision instance id def provision(r, data) id = data["id"] provision_config.update do |c| d = generate_database_name if c[id] r.fail(message: "Database already exists", type: :database_already_exists) else c[id] = { database: d, users: {} } end end r.succeed end # Bind database (create credentials) # Data is a hash with items: # * instance_id is provision instance id # * id is binding id # returns credentials object def bind(r, data) instance_id = data["instance_id"] id = data["id"] instance = nil config = provision_config.update do |c| instance = c[instance_id] return r.fail(message: "No database found", type: :no_database_found) unless instance user = instance[:users][id] return r.fail(message: "Already binded", type: :already_binded) unless user.nil? instance[:users][id] = { user: generate_user_name, password: generate_password } end credentials = build_credentials(instance[:database], config[:user], config[:password]) driver.connection.db(instance[:database]).collection("system.users"). safe_insert(user: config[:user], pwd: to_mongo_password(config[:user], config[:password]), roles: %w(readWrite dbAdmin)). callback { r.succeed(credentials: credentials) }. errback {|e| r.error(e)} end def unbind(r, data) instance_id = data["instance_id"] id = data["id"] instance = nil user = nil provision_config.update do |c| instance = c[instance_id] return r.fail(message: "No database found", type: :no_database_found) unless instance user = instance[:users][id] return r.fail(message: "Not binded", type: :not_binded) if user.nil? instance[:users].delete(id) end driver.connection.db(instance[:database]).collection("system.users"). remove(user: user[:user]) r.succeed({}) end def unprovision(r, data) id = data["id"] instance = nil provision_config.update do |c| instance = c[id] return r.fail(message: "No database found", type: :no_database_found) unless instance c.delete(id) end driver.connection.db(instance[:database]).command(dropDatabase: 1). callback{ r.succeed({}) }. errback{|e| r.fail({})} end def build_credentials(database, user, password) hosts = nodes.join(',') { # We use mongo_uri, because uri breaks staging url: "mongodb://#{user}:#{password}@#{hosts}/#{database}", username: user, password: password, hosts: nodes, database: database } end def generate_database_name "d" + SecureRandom.base64(20).gsub(/[^a-zA-Z0-9]+/, '')[0...16] end def generate_user_name "u" + SecureRandom.base64(20).gsub(/[^a-zA-Z0-9]+/, '')[0...16] end def generate_password "p" + SecureRandom.base64(20).gsub(/[^a-zA-Z0-9]+/, '')[0...16] end def to_mongo_password(login, password) Digest::MD5::hexdigest("#{login}:mongo:#{password}") end end end
# Q35 2つのデータベースからユーザーネーム・学習項目・合計学習時間のデータを取得したら以下のようになりました # [["田中", "JavaScript"], 30] # 上記の配列を以下のようなハッシュに変換してください # {"user_name" => "田中", "learning_contents" => "JavaScript", "learning_time" => 30} def q35 array = [["田中", "JavaScript"], 30] keyAry = ["user_name", "learning_contents", "learning_time"] keyValue = array.flatten ary = [keyAry, keyValue].transpose p ary.to_h end
class DropTableMateriaProfesors < ActiveRecord::Migration def change drop_table :materia_profesors, force: :cascade end end
class AdminsController < ApplicationController before_filter :authorized? def index end private def authorized? if current_user == nil flash[:error] = "Please sign in!" redirect_to root_path elsif current_user.role != "admin" flash[:error] = "You are not authorized to view that page." redirect_to root_path end end end
module Wunderlist class Resource class << self def class_name name.split("::").last end def url "#{class_name.downcase}s" end def all(client, params = {}) url = self.url if params.any? query_params = params.collect{ |key, val| "#{key}=#{val}" }.join("&") url = "#{url}?#{query_params}" end collection = client.get(url) collection.map{ |resource| new(resource, client) } end def find(client, id) response = client.get("#{url}/#{id}") new(response, client) end def create(client, payload = {}) response = client.post(url, payload) new(response, client) end def update(client, id, payload = {}) response = client.patch("#{url}/#{id}", payload) new(response, client) end def destroy(client, id, payload = {}) query_params = payload.map{|key, val| "#{key}=#{val}"}.join("&") delete_url = "#{url}/#{id}?#{query_params}" client.delete(delete_url) end end attr_reader :attributes, :client def initialize(attributes, client) @attributes = attributes @client = client end def url "#{self.class.url}/#{id}" end def update(payload = {}) payload.merge!(revision: revision) @attributes = client.patch(url, payload) true end def destroy client.delete("#{url}?revision=#{revision}") end def method_missing(method, *args, &block) method_key = method.to_s attributes.has_key?(method_key) ? attributes[method_key] : super end def respond_to_missing?(method, include_private = false) method_key = method.to_s attributes.has_key?(method_key) ? true : false end end end
class Staffs::RegistrationsController < Staffs::BaseController before_action :authenticate_staff! def edit @staff = current_staff end def update if update_password_params[:password] == update_password_params[:password_confirmation] current_staff.update(password: update_password_params[:password], reset_password: false) else redirect_to edit_staff_registration_path end end private def update_password_params params.require(:staff).permit(:password, :password_confirmation) end end
class ContactMailer < ApplicationMailer def contact_mail(contact) @contact = contact mail to:"lesage1510@gmail.com", subject: "Nous contacter" end end
#[4.6]例題:RGB変換プログラムを作成する #RGB変換プログラムの仕様を確認する。 # ・10進数を16進数に変換するto_hexメソッドと16進数を10進数に変換するto_intsメソッドの2つを定義する。 # ・to_hexメソッドは3つの整数を受け取り、それぞれ16進数に変換した文字列を返す。文字列の先頭には"#"をつける。 # ・to_intsメソッドはRGBカラーを表す16進数文字列を受け取り、R、G、Bのそれぞれを10進数の整数に変換した値を配列として返す。 # EX 実行例 puts to_hex(0, 0, 0) # ==> '#000000' puts to_hex(255, 255, 255) # ==> '#ffffff' puts to_hex(4, 60, 120) # ==> '#043c78' puts to_ints('#000000') # ==> [0, 0, 0] puts to_ints('#ffffff') # ==> [255, 255, 255] puts to_ints('#043c78') # ==> [4, 60, 120] #[4.6.1]to_hexメソッドを作成する #今回はto_hexメソッドのテストコードから作成していきます。いわゆる「テスト駆動開発(TDD、Test driven development)」というやつ。 #「プログラムのインプットとアウトプットが明確である」「テストコードの書き方が最初からイメージできる」という2つの条件が揃っている場合はTDDが向いています。 #今回のテストコード # ==> 「rgb_test.rb」に別途作成済み require 'minitest/autorun' class RgbTest < Minitest::Test def test_to_hex assert_equal '#000000', to_hex(0, 0, 0) end end # EX このままテストファイルを実行する 1) Error: RgbTest#test_to_hex: NoMethodError: undefined method 'to_hex' for #<RgbTest:0x00007fe82e8e1570> rgb_test.rb:5:in test_to_hex 1 runs, 0 assertions, 0 failures, 1 errors, 0 skips # ==> 案の定、テストは失敗しました。NoMethodErrorなので、「to_hex」が見つからない、定義されていないと言われています。 #それからrgb.rbを作成して下記内容を記述する。(別途作成済み) def to_hex(r, g, b) '#000000' end #ここではあえてロジックらしいロジックを書かずに、あえて'#000000'という固定の文字列を返しています。 #これはまず、テストコードがちゃんと機能しているか、とういうことをチェックするためです。 #テストファイルに今回作成したrgb.rbをテストコードに読み込ませます。 require 'minitest/autorun' require_relative './rgb.rb' # <== 新しく追加 class RgbTest < Minitest::Test def test_to_hex assert_equal '#000000', to_hex(0, 0, 0) end end #ひとまず、テストを実行してみましょう! Run options: --seed 4503 # Running: . Finished in 0.000717s, 1394.6999 runs/s, 1394.6999 assertions/s. 1 runs, 1 assertions, 0 failures, 0 errors, 0 skips #期待通り、テストをパスできました。しかし、これで満足してはいけません。テストコードにはもう一つ検証コードを追加します。 require 'minitest/autorun' require_relative './rgb.rb' class RgbTest < Minitest::Test def test_to_hex assert_equal '#000000', to_hex(0, 0, 0) assert_equal '#ffffff', to_hex(255, 255, 255) # <== 新しく追加 end end #テストを実行してみても、当たり前ですが失敗します。 1) Failure: RgbTest#test_to_hex [rgb_test.rb:7]: Expected: "#ffffff" Actual: "#000000" 1 runs, 2 assertions, 1 failures, 0 errors, 0 skips #ここで必要な作業は整数値を16進数に変換することです。これは「to_sメソッド」を使うと実現できます。 puts 0.to_s(16) # ==> "0" puts 255.to_s(16) # ==> "ff" #基本的にはto_sメソッドで16進数に変換できます。 #ところが、0の時は1桁の"0"になっています。こちらが期待しているのは"00"のような2桁の文字列です。 #今回の場合だとrjustメソッドを使って右寄せすると便利です。第1引数には桁数を指定します。デフォルトは空白(半角スペース)で桁揃えされますが、第2引数を指定すると、空白以外の文字列を埋めることができます。 puts '0'.rjust(5) # ==> " 0" puts '0'.rjust(5, '0') # ==> "00000" puts '0'.rjust(5, '_') # ==> "____0" #このメソッドを組み合わせれば、0を2桁の"00"に変換できますね。 puts 0.to_s(16).rjust(2, '0') # ==> "00" puts 255.to_s(16).rjust(2, '0') # ==> "ff" #次のようにrgb.rb内のto_hexメソッドをちゃんと実装できます。 def to_hex(r, g, b) '#' + r.to_s(16).rjust(2, "0") + g.to_s(16).rjust(2, "0") + b.to_s(16).rjust(2, "0") end #テストをパスできるか確認しましょう! # Running: . Finished in 0.000602s, 1661.1298 runs/s, 3322.2595 assertions/s. 1 runs, 2 assertions, 0 failures, 0 errors, 0 skips #テストもパスすることができました。 #念のため、r、g、bの各値がバラバラになっているテストも追加します。 require 'minitest/autorun' require_relative './rgb.rb' class RgbTest < Minitest::Test def test_to_hex assert_equal '#000000', to_hex(0, 0, 0) assert_equal '#ffffff', to_hex(255, 255, 255) assert_equal '#043c78', to_hex(4, 60, 120) # <== 新しく追加 end end #テストをパスしたら今度はリファクタリングをおこないます! #[4.6.2]to_hexメソッドをリファクタリングする #リファクタリングとは外から見た振る舞いは保ったまま、理解や修正が簡単にできるように内部のコードを改善することです。 #先程のto_hexメソッドを確認してみましょう! def to_hex(r, g, b) '#' + r.to_s(16).rjust(2, "0") + g.to_s(16).rjust(2, "0") + b.to_s(16).rjust(2, "0") end # ==> 今の状態だと「.to_s(16).rjust(2, "0")」が3回登場します。 #   これだと将来、何か変更があった時に同じ変更を3回繰り返さないといけません。 #プログラミングにはDRY原則と呼ばれる有名な原則があります。 #これは「Don't repeat yourself」の略で、「繰り返しを避けること」という意味です。DRY原則に従い、to_hexメソッドからコードの重複を取り除きましょう。 # 同じ処理を3回するのであれば、r、g、bの各値を配列に入れて繰り返し処理すれば済みそうです。 class RgbTest < Minitest::Test def test_to_hex(r, g, b) hex = "#" [r, g, b].each do |n| hex += n.to_s(16).rjust(2, "0") end puts hex end # ==> 上のコードでは[r, g, b]というように引数として渡された各値を配列に入れた後、eachメソッドを使って繰り返し処理しています。 # eachメソッドの内部では数値を16進数に変換した文字列を、ブロックの外で作成したhex変数に連結します。 # ==> そして最後に変数hexをメソッドに戻り値として返却しています。 # この結果、.to_s(16).rjust(2, "0")は一度しか登場しなくなりました。 #これでもテストをパスできるか確認してみましょう! Finished in 0.000883s, 1132.5029 runs/s, 3397.5086 assertions/s. 1 runs, 3 assertions, 0 failures, 0 errors, 0 skips #リファクタリングしてもテストをパスしましたね! #さらにinjectメソッドを使用すると、もっと短くコーディングできます! def test_to_hex(r, g, b) [r, g, b].inject('#') do |hex, n| hex + n.to_s(16).rjust(2, "0") end #ここでおさえておくべきポイントは3つあります。 # (1) 最初の繰り返し処理ではhexに'#'が入ること。 # (2) ブロックの中のhex + n.to_s(16).rjustu(2, '0')で作成された文字列は次の繰り返し処理のhexに入ること。 # (3) 繰り返し処理が最後まで到達したら、ブロックの戻り値がinjectメソッド自身の戻り値になること。 # ==> ここでピンと来ないときは「[4.4.4]inject/reduce」を読み直そう #[4.6.3]to_intsメソッドを作成する #16進数の文字列を10進数の数値3つに変換するメソッドです。 to_ints('#000000') # ==> [0, 0, 0] to_ints('#ffffff') # ==> [255, 255, 255] to_ints('#043c78') # ==> [4, 60, 120] #to_hexメソッドの時と同じようにテストコードを書き込みましょう! # EX rgb_test.rb class RgbTest < Minitest::Test def test_to_hex assert_equal '#000000', to_hex(0, 0, 0) assert_equal '#ffffff', to_hex(255, 255, 255) assert_equal '#043c78', to_hex(4, 60, 120) end def test_to_ints # 新しく追加 assert_equal [0, 0, 0], to_ints('#000000') # | end # | end #次にrgb.rbを開き、to_intsメソッドの仮実装します。 # EX rgb.rb def to_hex(r, g, b) [r, g, b].inject('#') do |hex, n| hex + n.to_s(16).rjust(2, "0") end end def to_ints(hex) # 新しく追加 [0, 0, 0] # | end # | # EX テストを実行してみる ryotaono@onoyuufutoshinoMacBook-Air cherry_book_two % ruby rgb_test.rb Run options: --seed 44069 # Running: .. Finished in 0.000693s, 2886.0032 runs/s, 5772.0064 assertions/s. 2 runs, 4 assertions, 0 failures, 0 errors, 0 skips #二つ目の検証コードを追加しましょう! # EX rgb_test.rb require 'minitest/autorun' require_relative './rgb.rb' class RgbTest < Minitest::Test def test_to_hex assert_equal '#000000', to_hex(0, 0, 0) assert_equal '#ffffff', to_hex(255, 255, 255) assert_equal '#043c78', to_hex(4, 60, 120) end def test_to_ints assert_equal [0, 0, 0], to_ints('#000000') assert_equal [255, 255, 255], to_ints('#ffffff') # <== 新しく追加 end end # EX テストを実行してみよう 1) Failure: RgbTest#test_to_ints [rgb_test.rb:13]: Expected: [255, 255, 255] Actual: [0, 0, 0] # ==> 失敗してしまいました…。 #to_intsメソッドの実装で必要な手順は大きく分けて次の2つです。 # ①文字列から16進数の文字列を2文字ずつ取り出す。 # ②2桁の16進数を10進数の整数に変換する。 #まず、16進数の文字列を2つずつ取り出す方法ですが、これは[]と範囲オブジェクトを使うことにします。 #「[4.5.1]配列と文字列の一部を抜き出す」のこうでも既に説明した通り、例えば、文字列の2文字目から4文字目までを取り出したい時は、次のように取り出すことができます。 # EX 範囲オブジェクトで取り出す方法 s = 'abcde' puts s[1..3] # ==> bcd #この方法を利用することによって次のようのに文字列からR(赤)、G(緑)、B(青)の各値を取り出すことができます。 # EX 文字列からR(赤)、G(緑)、B(青)の各値を取り出す方法 hex = '#12abcd' puts r = hex[1..2] # ==>12 puts g = hex[3..4] # ==>ab puts b = hex[5..6] # ==>cd #次に考えるのは16進数の文字列を10進数の整数に変更する方法です。 #これはstringクラスにhexというズバリそのもののメソッドがあります。 # EX hexクラス puts '00'.hex # ==> 0 puts 'ff'.hex # ==> 255 puts '2a'.hex # ==> 42 #さあ、これらの知識を結合すると、to_intsメソッドを次のように実装できます。 # EX rgb.rb内を下記のように書き換え def to_ints(hex) r = hex[1..2] g = hex[3..4] b = hex[5..6] ints = [] [r, g, b].each do |s| ints << s.hex end puts ints end #上のコードの処理フローは次の通りです。 # ・引数の文字列から3つの16進数を抜き出す。 # ・3つの16進数を配列に入れ、ループを回しながら10進数の整数に変換した値を別の配列に詰め込む。 # ・10進数の整数が入った配列を返す。 #テストを実行してみましょう! # EX テスト結果 #[4.6.4]to_intsメソッドをリファクタリングする #繰り返し処理の部分をmapメソッドに変更することができます。([4.4.1]map/collectを参照) # EX eachをmapに置き換える # ==> 「空の配列を用意して、他の配列をループ処理した結果を空の配列に詰め込んでいくような処理の大半はmapメソッドに置き換えることができるはずです。」 def to_ints(hex) r = hex[1..2] g = hex[3..4] b = hex[5..6] [r, g, b].map do |s| s.hex end puts ints end # ==> mapメソッドはブロックの戻り値を配列の要素にして新しい配列を返すメソッドですね。 # ==> なのでわざわざintsのような変数を用意しなくても、mapメソッドとブロックだけで処理が完結します。 #[4.6.5]to_intsメソッドをリファクタリングする(上級編) #初心者の方は前項まででもOKなのですが、Rubyに慣れてくるともっとコードを短くすることができます。 #ここでは参考までに熟練者向けのリファクタリング方法を紹介します。 #まず、最初にr、g, bという変数を作って代入していますが、ここは改行せずに多重代入を使って1行にしても、コードの可読性は悪くならないと思います。 def to_ints(hex) r, g, b = hex[1..2], hex[3..4], hex[5..6] # <== リファクタリング [r, g, b].map do |s| s.hex end end #さらに、範囲オブジェクトの代わりに正規表現とscanメソッドを使うと、一気に文字列を3つの16進数に分割できます。(正規表現は第6章で説明します。) def to_ints(hex) r, g, b = hex.scan(/\w\w/) # <== 正規表現に変更 [r, g, b].map do |s| s.hex end end # ==> scanメソッドは正規表現にマッチした文字列を配列にして返します。r, g, bに対して多重代入できるのもscanメソッドが配列を返しているためです。 puts '#12abcd'.scan(/\w\w/) # ==> ['12', 'ab', 'cd'] #なので、一度変数に入れて[r, g, b]のような配列を作らなくても、scanメソッドの戻り値に対して直接mapメソッドを呼ぶことができます。 def to_ints(hex) hex.scan(/\w\w/).map do |s| # <== s.hex end end #ところで、みなさんは少し前に説明した「[4.4.5]&とシンボルを使ってもっと簡素に書く」という項を覚えていますか? #この項では次の条件が揃った時にブロックの代わりに「&:メソッド名」という引数を渡すことができる、と説明しました。 # ・ブロック引数が1個だけである。 # ・ブロックの中で呼び出すメソッドには引数がない。 # ・ブロックの中では、ブロック引数に対してメソッドを1回呼び出す以外の処理がない。 #to_intsメソッドの中で書いているブロックの処理がまさにこれに該当します。というわけで、ブロックをなくし、代わりに「&:hex」を「mapメソッド」の引数に渡します。 def to_ints(hex) hex.scan(/\w\w/).map(&:hex) # <== end #このように、Rubyの提供している便利なメソッドや言語機能を使うと、ここまで簡素なコードを書くことができます。 #Ruby初心者の方は最初からこんなに短いコードを書くのは難し以下もしれませんが、自分の書いたコードにすぐに満足せず、どこかリファクタリングできる部分はないか研究をすることを心がけてください!
require 'spec_helper' describe ClimbingsController do subject { response } describe '#index' do let!(:climbings) { create_list :climbing, 2 } before { get :index } it { assigns(:climbings).should eq climbings } end describe '#new' do before { get :new } it { assigns(:climbing).should be_a_new(Climbing) } end describe 'create' do let!(:current_user) { create :user } let!(:gym) { create :gym } before { controller.stub(:current_user => current_user) } context 'with valid parameters' do before { post :create, :climbing => { :comment => 'My Comment', :gym_id => gym.id } } it { assigns(:climbing).should_not be_a_new(Climbing) } it { assigns(:climbing).user.should eq current_user } it { should redirect_to climbings_path } end end end
class SubscriptionsController < ApplicationController skip_before_filter :authenticate, only: [:index, :new, :create, :stripe_callback] skip_before_filter :verify_subscription, only: [:index, :new, :create, :stripe_callback] skip_before_filter :accept_terms, :check_for_interstitials, :complete_onboarding layout 'subscriptions' # # display the plans for the current offer # def index end # # handle login/registration & payment info # def new @return_path = new_subscription_path redirect_to subscriptions_path and return unless current_plan end # # apply new subscription info # def create @return_path = new_subscription_path redirect_to subscriptions_path and return unless current_plan render 'new' and return unless current_user current_user.update_stripe_card!(params[:stripe_card_token]) unless params[:stripe_card_token].blank? current_user.apply_coupon!(current_coupon.id) if current_coupon current_user.set_offer_and_subscription_plan!(current_offer, current_plan) if current_offer && current_plan unless current_user.stripe_subscription_active? Rails.logger.debug "current_user.stripe_subscription_active? is false" render 'new' and return end Resque.enqueue(UpdateMailChimp, current_user.email, :subscriber) Rails.logger.info "Subscription updated." clear_subscription_data process_new_subscription_analytics redirect_to subscription_confirm_path rescue Stripe::StripeError => e error = e.json_body[:error] # this POST happens twice. The first time through, the user hasn't entered any form data and we don't want to show bogus errors. unless params[:stripe_customer_id].nil? # first pass through won't include stripe_customer_id as a param Rails.logger.error error[:message] flash.alert = error[:message] end render 'new' rescue => e Rails.logger.error e.message flash.alert = "M2222"#e.message render 'new' end def destroy current_user.cancel_subscription! Resque.enqueue(UpdateMailChimp, current_user.email, :past_subscriber) redirect_to settings_path end def confirm @user = current_user # default notifications to true @user.receive_email_notifications = true if @user.receive_email_notifications.nil? @user.receive_sms_notifications = true if @user.receive_sms_notifications.nil? end def stripe_callback Resque.enqueue(HandleStripeCallback, params) head :ok end private def process_new_subscription_analytics # Mixpanel Tracking mixpanel_track('Created Subscription', {plan: current_plan.name}) push_mixpanel_event "mixpanel.people.track_charge(#{current_plan.price});" # fire a conversion pixel if the purchase source was "EverySignal" (any case). if current_lead && "EverySignal".casecmp(current_lead.source.to_s) session[:push_everysignal_pixel] = current_plan.price # value is the price end #for google/optimizely tracking js session[:purchase_information] = { transaction_id: "#{current_plan.stripe_plan_id}_#{Time.now.iso8601}", store_name: 'app Site', total: current_plan.discounted_price, tax: 0.0, shipping: 0.00, city: '', state: '', country: 'USA', sku: "#{current_plan.stripe_plan_id}", product_name: "#{current_plan.name}", category: "#{current_plan.offer.name}", unit_price: current_plan.price, quantity: 1, } end end
# frozen_string_literal: true # Documents class DocumentsController < ApplicationController before_action :set_document, only: %i[show edit update destroy] before_action :set_template, only: %i[show new edit update create index update] # GET /documents # GET /documents.json def index @documents = Document.all end # GET /documents/1 # GET /documents/1.json def show respond_to do |format| format.html format.pdf do render pdf: 'document.pdf', disposition: 'inline', template: 'documents/show.pdf.erb' end end end # GET /documents/new def new @document = Document.new end # GET /documents/1/edit def edit; end # POST /documents # POST /documents.json def create @document = create_with_answers respond_to do |format| if @document.save format.html { redirect_to template_document_path(@document.template_id, @document), notice: 'Document created' } format.json { render :show, status: :created, location: @document } else format.html { render :new } format.json { render json: @document.errors, status: :unprocessable_entity } end end end # PATCH/PUT /documents/1 # PATCH/PUT /documents/1.json def update respond_to do |format| if @document.update(document_params) format.html { redirect_to template_document_path(@document.template_id, @document), notice: 'Document updated' } format.json { render :show, status: :ok, location: @document } else format.html { render :edit } format.json { render json: @document.errors, status: :unprocessable_entity } end end end # DELETE /documents/1 # DELETE /documents/1.json def destroy @document.destroy respond_to do |format| format.html { redirect_to template_documents_url, notice: 'Document was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_document @document = Document.find(params[:id]) end def set_template @template = Template.find(params[:template_id]) end def create_with_answers @document = Document.new(document_params) params[:document]['answers']&.each do |q, answer| a = Answer.new({ question_id: q, content: answer }) @document.answers << a end @document.status = 'complete' if @document.answers.count == @template.questions.count @document end # Only allow a list of trusted parameters through. def document_params params.require(:document).permit(:status, :output, :template_id) end end
# WinRM module module WinRM # The version of the WinRM library VERSION = '2.3.3'.freeze end
module Loadrunner # Executes event hooks class Runner attr_reader :opts attr_accessor :response, :hooks_dir def initialize(opts) @hooks_dir = 'hooks' @opts = opts end # Execute all matching hooks based on the input payload. This method # populates the `#response` object, and returns true on success. def execute set_environment_vars @response = opts.dup hooks = locate_hooks @response[:matching_hooks] = matching_hooks if hooks.empty? @response[:error] = "Could not find any hook to process this request. Please implement one of the 'matching_hooks'." false else execute_all hooks @response[:executed_hooks] = hooks true end end private # Find all hooks that fit the payload meta data. def locate_hooks hooks = [] matching_hooks.each do |hook| hooks << hook if File.exist? hook end hooks end # Execute all hooks. def execute_all(hooks) hooks.each do |hook| run_bg hook end end # Run a command in the background. def run_bg(cmd) job = fork { exec cmd } Process.detach job end # Set all payload meta data as environment variables so that the # hook can use them. def set_environment_vars opts.each { |key, value| ENV["LOADRUNNER_#{key.to_s.upcase}"] = value } end def matching_hooks base = "#{hooks_dir}/#{opts[:repo]}/#{opts[:event]}" hooks = [ "#{hooks_dir}/global", "#{hooks_dir}/#{opts[:repo]}/global", base.to_s, ] hooks << "#{base}@branch=#{opts[:branch]}" if opts[:branch] if opts[:tag] hooks << "#{base}@tag=#{opts[:tag]}" hooks << "#{base}@tag" end hooks end end end
class ActivationsController < ApplicationController skip_authorization_check unless: :current_player def activate if current_player authorize! :update, current_player if current_player.active? flash[:alert] = "You were already in the queue." else current_player.update! active: true flash[:notice] = "You've been queued to play." end redirect_back fallback_location: root_path else flash[:alert] = "You must be logged in to join the queue." redirect_to new_player_session_path end end def deactivate if current_player authorize! :update, current_player if current_player.active? current_player.update! active: false flash[:notice] = "You've been removed from the queue." else flash[:alert] = "You weren't queued to play." end redirect_back fallback_location: root_path else flash[:alert] = "You must be logged in to leave the queue." redirect_to new_player_session_path end end end
class RemoveDiscapacidadesFromPaciente < ActiveRecord::Migration def change remove_column :pacientes, :discapacidades, :string end end
require 'spec_helper' describe Hoarder::Storage, "#initialize" do let(:config) { {:provider => 'rackspace', :rackspace_username => 'testguy', :rackspace_api_key => 'iamakey'} } let(:connection) { mock(Fog::Storage) } before { Fog::Storage.stub(:new).and_return(connection) } context "when config file is missing" do before { FileTest.stub(:exist?).and_return(false) } specify { lambda { Hoarder::Storage.new('') }.should raise_error(RuntimeError, "Missing config file /hoarder.yml.") } end context "when config file is not missing" do before { FileTest.stub(:exist?).and_return(true) File.stub(:open).and_return('') } context "and opening file causes exception" do specify { lambda { Hoarder::Storage.new('') }.should raise_error(RuntimeError, "Unable to load config file /hoarder.yml.") } end context "and opening file does not cause an exception" do context "and config file is empty" do before { YAML.stub(:load).and_return({}) } specify { lambda { Hoarder::Storage.new('') }.should raise_error(RuntimeError, "Unable to load config file /hoarder.yml.") } end end end end
module Toolbox module Tools class Dictionary < Base def self.will_handle /define .*/ end def self.help_text "define <word>" end def handle word = @input.match(/define (.*)/)[1] DictionaryEntry.get(word).to_s rescue DictionaryApiNotOKError => e "There was a problem connecting to the dictionary api" end private class DictionaryEntry def self.get word response = OxfordDictionaryApi.define word if response.success? new response.data[:results][0][:lexicalEntries] else DictionaryInflection.get(word) || DictionaryMisspellings.get(word) end end def initialize lexicalEntries @data = [] lexicalEntries.each do |lexicalEntry| @data << { category: lexicalEntry[:lexicalCategory].upcase, entries: lexicalEntry[:entries].map do |entry| entry[:senses].filter do |sense| sense[:definitions] end.map do |sense| domains = sense[:domains] return nil unless sense[:definitions] definition = sense[:definitions][0] if domains definition = "#{domains.join(", ")}: #{definition}" else definition[0] = definition[0].capitalize end definition end end } end end def to_s @data.map do |group| outer_prefix = @data.length > 1 ? "1. " : "" group_text = group[:entries].filter do |entry| entry.length > 0 end.map do |entry| entry_text = "" if entry.length > 1 inner_prefix = "a) " entry_text = entry.map do |sense| sense_text = "#{outer_prefix}#{inner_prefix}#{sense}" inner_prefix = inner_prefix.next sense_text end.join "\n\n" else entry_text = "#{outer_prefix}#{entry.first}" end outer_prefix = outer_prefix.next entry_text end.join "\n\n" group[:category] + "\n" + group_text end.join "\n\n" end end class DictionaryInflection def self.get word response = OxfordDictionaryApi.inflections word return nil unless response.success? new response.data[:results][0][:lexicalEntries] end def initialize lexicalEntries @inflections = lexicalEntries.map do |lexicalEntry| lexicalEntry[:inflectionOf][0][:text] end.uniq end def to_s "Did you mean\n" + @inflections.map do |inflection| " - #{inflection}" end.join("\n") end end class DictionaryApiNotOKError < StandardError end class DictionaryMisspellings def self.get word response = OxfordDictionaryApi.misspellings word raise DictionaryApiNotOKError.new unless response.success? new response.data[:results] end def initialize results @alternatives = results.map do |result| result[:word] end end def to_s return "🤦 Wow, that's not even close to a real word." unless @alternatives.any? "Did you mean\n" + @alternatives.map do |alternative| " - #{alternative}" end.join("\n") end end class OxfordDictionaryApi def self.define word get "/v1/entries/en/#{word}" end def self.inflections word get "/v1/inflections/en/#{word}" end def self.misspellings word get "/v1/search/en?q=#{word}&prefix=false" end private def self.get url request = Typhoeus::Request.new( "https://od-api.oxforddictionaries.com:443/api#{url}", headers: { "app_key" => Rails.application.credentials.integrations[:dictionary_key], "app_id" => Rails.application.credentials.integrations[:dictionary_id] } ) request.run ApiResult.new request.response end end class ApiResult attr_reader :data def initialize response @success = response.success? @success && @data = JSON.parse(response.response_body).with_indifferent_access end def success? @success end end end end end
require 'rubygems' require 'time' class BusRoute def initialize(route_file) @route_file = route_file end def get_actual_duration read_file return nil unless actual_times_posted? times = @actual_times.values.sort! duration = (times.last - times.first)/60.0 end def get_expected_duration read_file times = @expected_times.values.sort! duration = (times.last - times.first)/60.0 end def calculate_average_delay read_file return nil unless actual_times_posted? avg_time = @delays.values.inject(0) { |sum,n| sum += n }.to_f / @delays.length end def find_stop_with_longest_delay read_file return nil unless actual_times_posted? @delays.sort_by{|k,v| v}.last[0] end def find_length_of_longest_delay read_file return nil unless actual_times_posted? @delays.sort_by{|k,v| v}.last[1] end private def read_file @expected_times ||= Hash.new @actual_times ||= Hash.new @delays ||= Hash.new if @expected_times.empty? puts "READING FILE" file = File.open(@route_file) file.each_line do |line| stop, expected, actual = line.split(",") expected_numeric = Time.parse(expected.chomp).to_i @expected_times[stop] = expected_numeric unless actual.nil? actual_numeric = Time.parse(actual.chomp).to_i @actual_times[stop] = actual_numeric @delays[stop] = (actual_numeric - expected_numeric)/60.0 end end end @actual_times end def actual_times_posted? if @actual_times.nil? || @actual_times.empty? puts "There are no actual times on file for this route" return false else return true end end end # ============ # QUICK DEMO # ============ rfuture = BusRoute.new("route_future.txt") puts rfuture.get_actual_duration puts rfuture.get_expected_duration puts rfuture.calculate_average_delay puts rfuture.find_stop_with_longest_delay puts rfuture.find_length_of_longest_delay puts "=" * 25 rpast = BusRoute.new("route_past.txt") puts rpast.get_actual_duration puts rpast.get_expected_duration puts rpast.calculate_average_delay puts rpast.find_stop_with_longest_delay puts rpast.find_length_of_longest_delay
class CentroContratoProducto < ActiveRecord::Base attr_accessible :id, :centro_contrato_id, :producto_id, :cantidad, :precio_base, :precio_costo, :observacion scope :ordenado_id, -> {order("id")} scope :ordenado_id_desc, -> {order("id desc")} belongs_to :centro_contrato belongs_to :producto end
class CreateUserPetFollowShips < ActiveRecord::Migration def change create_table :user_pet_follow_ships do |t| t.references :user, index: true t.references :pet, index: true t.timestamps null: false end add_foreign_key :user_pet_follow_ships, :users add_foreign_key :user_pet_follow_ships, :pets end end
class FightersController < ApplicationController before_action :set_fighter, only: [:show, :update, :destroy] # GET /fighters def index @fighters = Fighter.all render json: @fighters end # GET /fighters/1 def show render json: @fighter end # POST /fighters def create @fighter = Fighter.new(fighter_params) if @fighter.save render json: @fighter, status: :created, location: @fighter else render json: @fighter.errors, status: :unprocessable_entity end end # PATCH/PUT /fighters/1 def update if @fighter.update(fighter_params) render json: @fighter else render json: @fighter.errors, status: :unprocessable_entity end end # DELETE /fighters/1 def destroy @fighter.destroy end private # Use callbacks to share common setup or constraints between actions. def set_fighter @fighter = Fighter.find(params[:id]) end # Only allow a list of trusted parameters through. def fighter_params params.fetch(:fighter, {}) end end
Then /^the dashboard editor has "([^\"]*)" rows and "([^\"]*)" columns$/ do |row_count, column_count| within('table#dashboard') do expect(page).to have_xpath(".//tr", :count => row_count) expect(page).to have_xpath(".//td", :count => column_count) end end Then /^the dashboard "([^\"]*)" has "([^\"]*)" panels$/ do |slug, number| list = find("##{slug}").all('li') expect list.size == number end
class Category < ActiveRecord::Base validates :Name, presence: true validates :Description, presence: true validates :slug, uniqueness: true has_many :items, :dependent => :destroy mount_uploader :icon, IconUploader mount_uploader :banner, AddUploader before_save :create_slug scope :category_search, -> (query) { where("\"Name\" like ? OR \"Description\" like ? ","%#{query}%","%#{query}%") } def create_slug self.slug = self.Name.parameterize end end
require 'spec_helper' describe Review do it { should belong_to :user } it { should belong_to :video } it { should validate_presence_of :rating } it { should validate_presence_of :video } it { should validate_presence_of :content } describe '#video_title' do it "returns the reviewed video's title" do sarah = Fabricate(:user) video = Fabricate(:video, title: "Monk") review = Fabricate(:review, user: sarah, video: video) expect(review.video_title).to eq "Monk" end end end
class CreateUser < ActiveRecord::Migration[5.0] def change create_table :users do |t| t.string :email t.string :first_name t.string :last_name t.integer :lock_version, :default => 0 t.string :crypted_password t.string :password_salt t.string :persistence_token t.string :single_access_token t.string :perishable_token t.integer :login_count, :default => 0, :null => false t.integer :failed_login_count, :default => 0, :null => false t.datetime :last_request_at t.datetime :current_login_at t.datetime :last_login_at t.string :current_login_ip t.string :last_login_ip t.boolean :active, :default => true t.boolean :approved, :default => true t.boolean :confirmed, :default => true t.timestamps end end end
describe "Viewing an individual genre" do before do @genre = Genre.create!(genre_attributes(name: "Thriller")) end it "show the genre's details" do # Arrange - N/A # Action visit genre_url(@genre) # Assert expect(current_path).to eq(genre_path(@genre)) expect(page).to have_text(@genre.name) end it "lists the movies in the genre" do # Arrange movie1 = Movie.create!(movie_attributes(title: "Iron Man")) movie2 = Movie.create!(movie_attributes(title: "Iron Man 2")) movie3 = Movie.create!(movie_attributes(title: "Mr. Bean")) @genre.movies << movie1 @genre.movies << movie2 # Action visit genre_url(@genre) # Assert expect(page).to have_text(movie1.title) expect(page).to have_text(movie2.title) expect(page).not_to have_text(movie3.title) end end
class SubscriptionController < ApplicationController respond_to :json before_filter :authorize before_action :find_company , :only =>[:index , :update] def index subscription = @company.subscription plans = Owner.find_by_role("Super Admin").plans.select("id , name , no_doctors , price , category") result = {} current_plans = [] no_practitioners =@company.users.doctors.count # To add subscription details subscription_details = {current_plan: subscription.name , avail_practi: no_practitioners , max_practi: subscription.doctors_no , next_billing_date: (subscription.purchase_date+30.days) , category: subscription.category , fee: subscription.cost , remaining_days: 30 -(Date.today.mjd-subscription.purchase_date.mjd) } # To show list all plans.each do |plan| if plan.name == subscription.try(:name) && plan.category == subscription.try(:category) item = {id: subscription.id, name: subscription.name , no_doctors: subscription.doctors_no , price: subscription.cost , category: subscription.category , is_selected: true } else if no_practitioners > plan.no_doctors item = {id: plan.id, name: plan.name , no_doctors: plan.no_doctors , price: plan.price , category: plan.category , is_selected: false , not_available: true } else item = {id: plan.id, name: plan.name , no_doctors: plan.no_doctors , price: plan.price , category: plan.category , is_selected: false} end end current_plans << item end result[:subscription_detail] = subscription_details result[:plans] = current_plans render :json => result end def update plan = Plan.find(params[:id]) rescue nil # TO update plan with current date unless plan.nil? subscription = @company.subscription status = subscription.update_attributes( name: plan.name , doctors_no: plan.no_doctors, purchase_date: Date.today, cost: plan.price, category: plan.category ) if status result ={flag: status } render :json => result else show_error_json(subscription.errors.messages) end else result ={flag: false} render :json => result end end end
#!/usr/bin/ruby ALPHABET = [*'a'..'z', *'A'..'Z', *'0'..'9'] def gen_key(len) Array.new(len) { ALPHABET.sample }.join end KEY = gen_key(3) plain = ARGF.read cipher = plain.chars.zip(KEY.chars.cycle).map do |c, k| (c.ord ^ k.ord).tap { |x| $stderr.puts "c: #{c}, k: #{k}, x: #{x}" }.chr end.join puts cipher $stderr.puts "\nencrypted with #{KEY}"
When(/^customer clicks on enroll button after giving his user name and password$/) do end Then(/^customer is shown the MFA questions page$/) do sleep 5 puts "MFA Page Opened" end And(/^on the MFA page sees the header "([^"]*)"$/) do |header| expect(on(Cardenrollmentmfapage).mfa_header).to include header end # And(/^on the MFA page sees a label "([^"]*)"$/) do |label| # sleep 1.1 # expect(on(Cardenrollmentmfapage).mfa_label).to include label # end And(/^on the MFA page see the message "([^"]*)"$/) do |message| expect(on(Cardenrollmentmfapage).mfa_message).to include message end And(/^then clicks on the button Save My Security Settings to save his response and go to next page$/) do puts on(Cardenrollmentmfapage).mfa_save_button sleep 5 end And(/^on the MFA page has option to select the first question and enter (.*) in response$/) do |answer_1| on(Cardenrollmentmfapage).questions_set_1= on(Cardenrollmentmfapage).questions_set_1_options[1] on(Cardenrollmentmfapage).question_1_response= answer_1 end And(/^on the MFA page has option to select the second question and enter (.*) in response$/) do |answer_2| on(Cardenrollmentmfapage).questions_set_2= on(Cardenrollmentmfapage).questions_set_2_options[2] on(Cardenrollmentmfapage).question_2_response= answer_2 end And(/^on the MFA page has option to select the third question and enter (.*) in response$/) do |answer_3| on(Cardenrollmentmfapage).questions_set_3= on(Cardenrollmentmfapage).questions_set_3_options[3] on(Cardenrollmentmfapage).question_3_response= answer_3 end And(/^on the MFA page has option to select the fourth question and enter (.*) in response$/) do |answer_4| on(Cardenrollmentmfapage).questions_set_4= on(Cardenrollmentmfapage).questions_set_4_options[4] on(Cardenrollmentmfapage).question_4_response= answer_4 end And(/^on the MFA page has option to select the fifth question and enter (.*) in response$/) do |answer_5| on(Cardenrollmentmfapage).questions_set_5= on(Cardenrollmentmfapage).questions_set_5_options[5] on(Cardenrollmentmfapage).question_5_response= answer_5 end Given(/^a new customer is trying to enroll from iCORE using guid$/) do DataMagic.load('card_enrollment.yml') on(Linkuser) do |page| url_text = page.data_for(:enrollment_urls)['processing_url'] + page.data_for(:GUIDs)['unenrolled_mfa'] page.navigate_to url_text end end And(/^the answer completed status circles should be displayed$/) do expect(on(Cardenrollmentmfapage).completed_circle_1_element.visible?).to be true expect(on(Cardenrollmentmfapage).completed_circle_2_element.visible?).to be true expect(on(Cardenrollmentmfapage).completed_circle_3_element.visible?).to be true expect(on(Cardenrollmentmfapage).completed_circle_4_element.visible?).to be true expect(on(Cardenrollmentmfapage).completed_circle_5_element.visible?).to be true end Then(/^the user is taken to Activate Your Card page$/) do expect(on(Cardenrollmentmfapage).text).to include 'You’ll need your card to finalize access!' expect(on(Cardenrollmentmfapage).text).to include 'For your security, you must have your card to activate your online account.' end
module Grouping module Matching class Email # emailregex.com # EMAIL_REGEX_STRING = <<-EMAIL # (?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\]) # EMAIL # PATTERN = %r[EMAIL_REGEX_STRING] PATTERN = %r"(?-mix:[a-zA-Z0-9.!\#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)" # URI::MailTo::EMAIL_REGEXP sans worddelimiters def self.match(input:) matches = input.scan(PATTERN) ->{yield matches if block_given?}[] unless matches.empty? matches end end end end
class AttachmentRenderer < ResourceRenderer::AttributeRenderer::Base def display(attribute_name, label, options = {}, &block) options.reverse_merge!(format: :long) format = options.delete(:format) h.link_to(value_for_attribute(attribute_name).url) do h.tag(:span, class: 'btn btn-xs btn-primary btn-responsive') + h.content_tag(:span, h.t(".download"), class: 'btn-text') end end end
module Ricer::Plugins::Debug class Chandebug < Ricer::Plugin trigger_is :cdbg permission_is :operator has_usage :execute, '', :scope => :channel has_usage '<channel>' def execute(channel=nil) channel ||= self.channel rply(:msg_chaninfo, channel: channel.displayname, server: channel.server.displayname, ) end end end
module TrackerApi module Endpoints class Review attr_accessor :client def initialize(client) @client = client end def update(review, params = {}) raise ArgumentError, 'Valid review required to update.' unless review.instance_of?(Resources::Review) data = client.put("/projects/#{review.project_id}/stories/#{review.story_id}/reviews/#{review.id}", params: params).body review.attributes = data review.clean! review end end end end
require_relative 'spec_helper' # The SiegeEngine is very effective against buildings such as the Barracks. # It is however ineffective against other units (can't attack them, # as though they were dead). # # So unlike with Footman (whose attacks do a fraction of the damage # they normally would), the SiegeEngine does 2x the damage against # the Barracks # # Also, Siege Engines can attack other siege engines even though # they cannot attack any other units (such as Peasants or Footmen) describe SiegeEngine do before :each do @siegeEngine = SiegeEngine.new @barracks = Barracks.new end describe "#attack!" do it "should do deal (100) damage to the barracks" do @siegeEngine.attack!(@barracks) expect(@barracks.health_points).to eq(400) #starts at 500 end end describe "#attack!" do it "should deal (50) damage to another Siege Engine" do enemy = SiegeEngine.new @siegeEngine.attack!(enemy) expect(enemy.health_points).to eq(350) #starts with 400 end end describe "#attack!" do it "should deal (0) damage to an enemy Footman" do enemy = Footman.new @siegeEngine.attack!(enemy) expect(enemy.health_points).to eq(60) #starts with 60 end end describe "#attack!" do it "should deal (0) damage to a Peasant" do enemy = Peasant.new @siegeEngine.attack!(enemy) expect(enemy.health_points).to eq(35) #starts with 35 end end end
class CreateTables < ActiveRecord::Migration def change create_table :artists do |t| t.string :artist_name end create_table :songs do |t| t.string :song_name t.integer :artist_id t.integer :song_genre_id end create_table :song_genres do |t| t.integer :song_id t.integer :genre_id end create_table :genres do |t| t.string :genre_name t.integer :song_genre_id end end end
require 'test_helper' class CerttestsControllerTest < ActionController::TestCase setup do @certtest = certtests(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:certtests) end test "should get new" do get :new assert_response :success end test "should create certtest" do assert_difference('Certtest.count') do post :create, certtest: { description: @certtest.description, name: @certtest.name, project_id: @certtest.project_id } end assert_redirected_to certtest_path(assigns(:certtest)) end test "should show certtest" do get :show, id: @certtest assert_response :success end test "should get edit" do get :edit, id: @certtest assert_response :success end test "should update certtest" do patch :update, id: @certtest, certtest: { description: @certtest.description, name: @certtest.name, project_id: @certtest.project_id } assert_redirected_to certtest_path(assigns(:certtest)) end test "should destroy certtest" do assert_difference('Certtest.count', -1) do delete :destroy, id: @certtest end assert_redirected_to certtests_path end end
require 'aws-sdk' class Report < ActiveRecord::Base attr_accessible :cover_image, :cover_image_content_type, :cover_image_file_size, :pdf_report, :pdf_report_content_type, :pdf_report_file_size, :user_id, :job_id has_attached_file :cover_image, :storage => :s3, :s3_credentials => Rails.root.join('config', 's3_config.yml').to_s, :path => '/reports/:id/images/:filename' has_attached_file :pdf_report, :storage => :s3, :s3_credentials => Rails.root.join('config', 's3_config.yml').to_s, :path => '/reports/:id/pdfs/:filename' validates_attachment_content_type :cover_image, :content_type => ["image/jpg", "image/jpeg"] do_not_validate_attachment_file_type :pdf_report belongs_to :job def renderPDF @report = self puts "##### About to create report #{@report.id}" @job = Job.find(@report.job) @inspections = Inspection.where(:job_id => @job.id) @technicians = User.where("company_id = ? and role = 'technician'", @job.company_id) user = User.find(@report.user_id) @company = Company.find(user.company) #fire dampers summary @floor_totals = Hash.new @floor_percentage_totals = Hash.new @floor_totals["fire"] = @floor_percentage_totals["fire"] = @floor_totals["smoke"] = @floor_percentage_totals["smoke"] = @floor_totals["pass"] = @floor_percentage_totals["pass"] = @floor_totals["fail"] = @floor_percentage_totals["fail"] = @floor_totals["vine"] = @floor_percentage_totals["vine"] = @floor_totals["repair"] = @floor_percentage_totals["repair"] = @floor_totals["total"] = @floor_percentage_totals["total"] = 0; @floor_summaries = Array.new @floor_percentages = Array.new total_inspections = @inspections.count inspection_floors = @inspections.select('floor').all(:group => 'floor', :conditions => ["job_id = ?", @job.id]) inspection_floors.each do |inspection_floor| floor = inspection_floor.floor summary = Hash.new percentages = Hash.new summary["floor"] = floor percentages["floor"] = floor summary["fire"] = @inspections.count(:all, :conditions => ["floor = ? and damper_type_id = ?", floor, DamperType.where(:abbrev => "ECD")]) @floor_totals["fire"] += summary["fire"] percentages["fire"] = (summary["fire"].to_f / total_inspections.to_f) * 100.0 @floor_percentage_totals["fire"] += percentages["fire"] summary["smoke"] = @inspections.count(:all, :conditions => ["floor = ? and damper_type_id = ?",floor, DamperType.where(:abbrev => "PCD")]) @floor_totals["smoke"] += summary["smoke"] percentages["smoke"] = (summary["smoke"].to_f / total_inspections.to_f) * 100.0 @floor_percentage_totals["smoke"] += percentages["smoke"] summary["pass"] = @inspections.count(:all, :conditions => ["floor = ? and damper_status_id = ?",floor, DamperStatus.where(:abbrev => "OK")]) @floor_totals["pass"] += summary["pass"] percentages["pass"] = (summary["pass"].to_f / total_inspections.to_f) * 100.0 @floor_percentage_totals["pass"] += percentages["pass"] summary["fail"] = @inspections.count(:all, :conditions => ["floor = ? and damper_status_id = ?", floor, DamperStatus.where(:abbrev => "FAIL")]) @floor_totals["fail"] += summary["fail"] percentages["fail"] = (summary["fail"].to_f / total_inspections.to_f) * 100.0 @floor_percentage_totals["fail"] += percentages["fail"] summary["vine"] = @inspections.count(:all, :conditions => ["floor = ? and nonaccessible = 'TRUE'", floor]) @floor_totals["vine"] += summary["vine"] percentages["vine"] = (summary["vine"].to_f / total_inspections.to_f) * 100.0 @floor_percentage_totals["vine"] += percentages["vine"] summary["repair"] = @inspections.count(:all, :conditions => ["floor = ? and replace = 'TRUE'", floor]) @floor_totals["repair"] += summary["repair"] percentages["repair"] = (summary["repair"].to_f / total_inspections.to_f) * 100.0 @floor_percentage_totals["repair"] += percentages["repair"] summary["total"] = @inspections.count(:all, :conditions => ["floor = ?", floor]) @floor_totals["total"] += summary["total"] percentages["total"] = (summary["total"].to_f / total_inspections.to_f) * 100.0 @floor_percentage_totals["total"] += percentages["total"] @floor_summaries.push(summary) @floor_percentages.push(percentages) end @inspections = Inspection.where(:job_id => @job.id).order("tag ASC") puts "##### Collected all data for report #{@report.id}" # setup paths view_path = Rails.root.join('app','views','reports') # parse erb templates body = File.read(view_path.join('show.pdf.erb')) body_render = ERB.new(body).result(binding) puts "##### About to render PDF #{@report.id}" # run through wicked_pdf pdf = WickedPdf.new.pdf_from_string(body_render, :layout => false, :margin => { :left => 20, :right => 20, :top => 20 }, :page_height => '11in', :page_width => '8in' ) puts "##### Saving temp PDF report #{@report.id}" # then save to a file file = StringIO.new(pdf) #mimic a real upload file file.class.class_eval { attr_accessor :original_filename, :content_type } #add attr's that paperclip needs file.original_filename = "#{@report.id}.pdf" #assign filename in way that paperclip likes file.content_type = 'application/pdf' @report.pdf_report = file @report.save puts "##### Done! #{@report.id}" end end
# Write a method that will return a substring based on specific indices. def substring(word, start, finish=nil) return word[start] if finish.nil? word[start..finish] end p substring("honey", 0, 2) # => "hon" p substring("honey", 1, 2) # => "on" p substring("honey", 3, 9) # => "ey" p substring("honey", 2) # => "n"
require 'rails_helper' describe Snapshot do describe "validations" do before(:each) do @snapshot = FactoryBot.create(:snapshot) end it { is_expected.to validate_presence_of(:category) } it { is_expected.to validate_presence_of(:item) } it { is_expected.to validate_presence_of(:count) } it { is_expected.to validate_presence_of(:snapshot_date) } end describe ".take_snapshot" do it "should create a record for each membership type and billing plan" do nbr_records = Member::BILLING_PLANS.count + Member::MEMBER_TYPES.count expect { Snapshot.take_snapshot }.to change(Snapshot, :count).by(nbr_records) end end end
require 'bacon' require 'tilt' begin require 'jabs' describe Tilt::JabsTemplate do it "is registered for '.jabs' files" do Tilt['test.jabs'].should.equal Tilt::JabsTemplate end it "compiles and evaluates the template on #render" do template = Tilt::JabsTemplate.new { |t| ":ready" } template.render.should.equal `echo ":ready" | jabs`.chomp end end rescue LoadError => boom warn "Tilt::Jabs (disabled)\n" end
class AddCompdateToRubyStatus < ActiveRecord::Migration[5.0] def change add_column :ruby_statuses, :ga_1_compd, :date add_column :ruby_statuses, :ga_2_compd, :date add_column :ruby_statuses, :ga_3_compd, :date add_column :ruby_statuses, :ga_4_compd, :date add_column :ruby_statuses, :ga_5_compd, :date end end
# @private class String # @private def blank? self =~ /^\s*$/ end end # @private class NilClass # @private def blank? true end end # @private class Array # @private -- Credit to DHH and the Rails team def in_groups_of(number, fill_with = nil) if fill_with == false collection = self else # size % number gives how many extra we have; # subtracting from number gives how many to add; # modulo number ensures we don't add group of just fill. padding = (number - size % number) % number collection = dup.concat([fill_with] * padding) end if block_given? collection.each_slice(number) { |slice| yield(slice) } else returning [] do |groups| collection.each_slice(number) { |group| groups << group } end end end end # @private class Object # @private -- Credit to DHH and the Rails team def returning(value) yield(value) value end end # @private class Hash # @private -- credit to Trans, Jan Molic, Facets team def self.autonew(*args) leet = lambda { |hsh, key| hsh[key] = new( &leet ) } new(*args,&leet) end end
require_relative 'spec_helper' # TODO.... -_- # May be store structures with string representation? Because tests sux right now=( describe Terrazine::Constructor do before :each do @constructor = Terrazine.new_constructor end before :all do @permanent_c = Terrazine.new_constructor end it 'mrgl' do expect(@constructor.class).to eql Terrazine::Constructor end context '`WITH`' do it 'build array like syntax' do @constructor.with [:name, { select: true }] expect(@constructor.build_sql).to eq 'WITH name AS (SELECT * ) ' end it 'build nested array like syntax' do @constructor.with [[:name, { select: true }], [:another_name, { select: :mrgl }]] expect(@constructor.build_sql).to eq 'WITH name AS (SELECT * ), another_name AS (SELECT mrgl ) ' end it 'build hash like syntax' do @constructor.with name: { select: true }, another_name: { select: :mrgl } expect(@constructor.build_sql).to eq 'WITH name AS (SELECT * ), another_name AS (SELECT mrgl ) ' end end context '`SELECT`' do it 'build simple structure' do @constructor.select(:name) @constructor.select('phone') expect(structure(:select)).to eql [:name, 'phone'] end it 'build hash structure' do @constructor.select(u: [:name, :email]) @constructor.select _calls_count: [:_count, :connected] expect(structure(:select)).to eq u: [:name, :email], _calls_count: [:_count, :connected] expect(@constructor.build_sql).to eq 'SELECT u.name, u.email, COUNT(connected) AS calls_count ' end it 'build sub_queries' do @constructor.select select: [:_count, [:_nullif, :connected, true]], from: [:calls, :c], where: 'u.id = c.user_id' expect(@constructor.build_sql).to eq 'SELECT (SELECT COUNT(NULLIF(connected, true)) FROM calls c WHERE u.id = c.user_id ) ' end it 'build big structures' do @permanent_c.select _calls_count: { select: [:_count, [:_nullif, :connected, true]], from: [:calls, :c], where: { u__id: :c__user_id } }, u: [:name, :phone, { _master: [:_nullif, :role, "'master'"] }, 'u.abilities, u.id', 'birthdate'] @permanent_c.select o: :client_name @permanent_c.select :secure_id expect(@permanent_c.build_sql).to eq "SELECT (SELECT COUNT(NULLIF(connected, true)) FROM calls c WHERE u.id = c.user_id ) AS calls_count, u.name, u.phone, NULLIF(u.role, 'master') AS master, u.abilities, u.id, u.birthdate, o.client_name, secure_id " end it 'build DISTINCT' do @constructor.distinct_select([:id, :name, :phone]) expect(@constructor.build_sql).to eq 'SELECT DISTINCT id, name, phone ' end it 'build DISTINCT ON field' do @constructor.distinct_select([:id, :name, :phone], :id) expect(@constructor.build_sql).to eq 'SELECT DISTINCT ON(id) id, name, phone ' end it 'build DISTINCT ON array of field' do @constructor.distinct_select([:id, :name, :phone], [:id, :phone]) expect(@constructor.build_sql).to eq 'SELECT DISTINCT ON(id, phone) id, name, phone ' end end context '`FROM`' do it 'build simple data structures' do @constructor.from :users expect(@constructor.build_sql).to eq 'FROM users ' @permanent_c.from [:users, :u] expect(@permanent_c.build_sql).to match 'o.client_name, secure_id FROM users u $' end it 'build VALUES' do @constructor.from [:_values, [:_params, 'mrgl'], :r, ['type']] expect(@constructor.build_sql).to eq ['FROM (VALUES($1)) AS r (type) ', ['mrgl']] end it 'build VALUES and tables' do @constructor.from [[:mrgl, :m], [:_values, [1, 2], :rgl, [:zgl, :gl]]] expect(@constructor.build_sql).to eq 'FROM mrgl m, (VALUES(1, 2)) AS rgl (zgl, gl) ' end it 'build VALUES with many rows' do @constructor.from [:_values, [[:_params, 'mrgl'], [:_params, 'rgl']], :r, ['type']] expect(@constructor.build_sql).to eq ['FROM (VALUES($1), ($2)) AS r (type) ', ['mrgl', 'rgl']] end end context '`JOIN`' do it 'build simple structure' do @constructor.join 'users u ON u.id = m.user_id' expect(@constructor.build_sql).to eq 'JOIN users u ON u.id = m.user_id ' @constructor.join ['users u ON u.id = m.user_id', 'skills s ON u.id = s.user_id'] expect(@constructor.build_sql).to eq 'JOIN users u ON u.id = m.user_id JOIN skills s ON u.id = s.user_id ' end it 'build big structures' do @permanent_c.join [[[:masters, :m], { on: 'm.user_id = u.id' }], [[:attachments, :a], { on: ['a.user_id = u.id', 'a.type = 1'], option: :left}]] expect(@permanent_c.build_sql).to match 'FROM users u JOIN masters m ON m.user_id = u.id LEFT JOIN attachments a ON a.user_id = u.id AND a.type = 1 $' end end context '`ORDER`' do it 'build string structre' do @constructor.order 'name ASC' expect(@constructor.build_sql).to eq 'ORDER BY name ASC ' end it 'build array structure' do @constructor.order [:name, :email] expect(@constructor.build_sql).to eq 'ORDER BY name, email ' end it 'build hash structure' do @constructor.order name: :asc, phone: [:first, :desc] expect(@constructor.build_sql).to eq 'ORDER BY name ASC, phone DESC NULLS FIRST ' end it 'build complicated structure' do @constructor.order [:role, { name: :asc, phone: [:last, :desc], amount: '<' }] expect(@constructor.build_sql).to eq 'ORDER BY role, name ASC, phone DESC NULLS LAST, amount USING< ' end end context '`WHERE`' do it 'build simple structure' do @constructor.where [[:not, 'z = 13'], [:or, 'mrgl = 2', 'rgl = 22'], [:or, 'rgl = 12', 'zgl = lol']] expect(@constructor.build_sql).to eq 'WHERE NOT z = 13 AND (mrgl = 2 OR rgl = 22) AND (rgl = 12 OR zgl = lol) ' end it 'build intemidate structure' do @constructor.where [{ role: 'manager', id: [0, 1, 153] }, [:not, [:like, :u__name, 'Aeonax']]] expect(@constructor.build_sql).to eq ['WHERE role = $1 AND id IN ($2) AND NOT u.name LIKE $3 ', ['manager', [0, 1, 153], 'Aeonax']] end end context 'Operators' do it 'build missing operator' do sql = Terrazine.build_sql([:_to_json, [:_array_agg, { select: [:id, :title, { _copies_in_stock: { select: [:_count, :id], from: [:book_copies, :b_c], where: ['b_c.shop_id = s.id', 'b_c.book_id = b.id', 'NOT b_c.sold = TRUE'] } }] }]], key: 'operator') expect(sql).to eq 'to_json(array_agg((SELECT id, title, (SELECT COUNT(id) FROM book_copies b_c WHERE b_c.shop_id = s.id AND b_c.book_id = b.id AND NOT b_c.sold = TRUE ) AS copies_in_stock )))' end end end
require 'grape' require 'grape-swagger' class API < Grape::API # use Rack::Session::Cookie # When there's an error, this is what to due, send it back as JSON # rescue_from :all, :backtrace => false rescue_from :all, backtrace: false do |e| message = (Rails.env == 'production' ? I18n.t('api.default_error') : e.message) Rack::Response.new({success: false, message: message, error: 403}.to_json, 201) end # if Rails.env.production? || Rails.env.staging? # extend NewRelic::Agent::Instrumentation::Rack # end default_error_formatter :json format :json default_format :json version 'v1.2', using: :path, vendor: 'Halalgems' # Import any helpers that you need helpers APIHelpers before do api_authenticate force_utf8_params end # Mount all API module mount UsersAPI mount RestaurantsAPI mount StaticPagesAPI mount FiltersAPI # add_swagger_documentation add_swagger_documentation markdown: true, api_version: 'v1.2', hide_documentation_path: true end
class WorkExperiencesController < ApplicationController skip_before_action :login_required, only: [:index, :show, :tag_index] before_action :set_work_experience, only: [:edit, :update, :destroy] before_action :forbid_work_experience_user, only: [:edit, :update, :destroy] def index if params[:q].present? params[:q]['title_or_tags_name_or_user_name_cont_any'] = params[:q]['title_or_tags_name_or_user_name_cont_any'].split(/[\p{blank}\s]+/) set_ransack_work_experience else set_ransack_work_experience end end def show @work_experience = WorkExperience.find(params[:id]) current_user.looked_history_create(@work_experience) if current_user&.work_experiences.present? @work_experience_comments = @work_experience.work_experience_comments.page(params[:page]).per(5).created_at_paging else @work_experience_comments = @work_experience.work_experience_comments.limit(5).created_at_paging end @work_experience_comment = WorkExperienceComment.new end def new @work_experience = WorkExperience.new end def create @work_experience = current_user.work_experiences.new(we_params) if @work_experience.save redirect_to @work_experience, notice: "記事「#{@work_experience.title}」を投稿しました。" else render :new end end def edit end def update if @work_experience.update(we_params) redirect_to work_experience_path, notice: "記事「#{@work_experience.title}」を更新しました。" else render :edit end end def destroy @work_experience.destroy redirect_to user_path(@current_user), notice: "記事「#{@work_experience.title}」を削除しました。" end def tag_index @q = WorkExperience.ransack(params[:q]) @work_experiences = WorkExperience.tagged_with("#{params[:tag_name]}").page(params[:page]).updated_at_paging end private def we_params params.require(:work_experience).permit(:title, :body, :tag_list) end def set_work_experience @work_experience = current_user.work_experiences.find_by(id: params[:id]) end def set_ransack_work_experience @q = WorkExperience.ransack(params[:q]) @work_experiences = @q.result(distinct: true).includes(:user).page(params[:page]).updated_at_paging end def forbid_work_experience_user redirect_to user_url(@current_user), notice: '権限がありません' unless @work_experience && @current_user.id == @work_experience.user_id end end
# encoding: UTF-8 class CFile def open Collecte.mode_test? && return `open "#{path}"` end def save content.to_s != '' || return # On s'assure que le dossier existe folder_exist? || build_folder File.open(path,'wb'){|f| f.write content} end def read File.exist?(path) || (return '') File.read(path) end # Construit le dossier (même s'il est dans une longue # hiérarchie inexistante) def build_folder `mkdir -p "#{folder}"` end end
require 'phraseapp-ruby' class PhraseAppClient def initialize(project_id: nil, token: nil) @project_id = project_id || Settings.phraseapp.project_id @token = token || Settings.phraseapp.api_token || '' credentials = PhraseApp::Auth::Credentials.new(token: @token) @client = PhraseApp::Client.new(credentials) end def logger @logger ||= if log_file = Settings.phraseapp.log_file Logger.new(log_file) else Rails.logger end end def delete_translation(model) deleted = 0 model.class.translatable_attributes.each do |attribute| key = model.build_translation_key(attribute) params = PhraseApp::RequestParams::KeysDeleteParams.new(q: key) affected = @client.keys_delete(@project_id, params).first.records_affected if affected.to_s == '0' else deleted = deleted + affected end end deleted end def get_all_translations(locales) translations = [] locales.each do |locale| translationsForLocale = download_locale(locale) translationsForLocale.each do |type, translationForType| translationForType.each do |id, translationValues| translationValues.each do |key, value| translations.push({ id: id, type: type, language: locale, key: key, content: value }) end end end end translations end def upload_translation_file_for_locale(file, locale, tags: nil) begin params = PhraseApp::RequestParams::UploadParams.new( file: file.path, update_translations: true, tags: tags || '', encoding: 'UTF-8', file_format: 'nested_json', locale_id: locale ) @client.upload_create(@project_id, params) rescue => exception message = 'Could not upload file ' message << "for the following error: #{exception.message}\n" message << "#{exception.backtrace[0..14].join("\n")}" logger.error message raise message if Rails.env.development? end end def delete_all_keys begin params = PhraseApp::RequestParams::KeysDeleteParams.new(q: '*') @client.keys_delete(@project_id, params).first.records_affected rescue => exception if exception =~ 'unexpected status code (504) received' logger.warn 'PhraseAppServer timed out while deleting all keys.' -1 else message = 'Could not delete all keys for ' message << "the following error: #{exception.message}\n" message << "#{exception.backtrace[0..14].join("\n")}" logger.error message raise message if Rails.env.development? end end end def delete_keys_by_name(keys) keys = keys.dup count_deleted = 0 while keys.any? do keys_to_process = keys.shift(300) q = 'name:' + keys_to_process.join(',') params = PhraseApp::RequestParams::KeysDeleteParams.new(q: q) count_deleted += @client.keys_delete(@project_id, params).first.records_affected end count_deleted end def delete_all_area_tags Translatable::AREAS.each do |area| delete_tag(area) end end def tag_all_areas num_tagged = 0 Translatable::AREAS.each do |area| models_in_area = Orga.where(area: area) + Event.where(area: area) + DataModules::Offer::Offer.where(area: area) + DataModules::FeNavigation::FeNavigationItem.joins(:navigation).where(fe_navigations: {area: area}) num_tagged += tag_models(area, models_in_area) end num_tagged end def delete_tag(tag) @client.tag_delete(@project_id, tag) rescue => exception if exception.message =~ /not found/ Rails.logger.info "There is not tag to delete called #{tag}" else raise exception end end def get_count_keys_for_tag(tag) begin result = @client.tag_show(@project_id, tag) result.first.keys_count rescue => exception 0 end end def tag_models(tags, models) models = models.dup records_affected = 0 while models.any? do models_to_process = models.shift(300) keys = [] models_to_process.each do |model| keys << model.build_translation_key('title') if model.respond_to?('short_description') # orga, event keys << model.build_translation_key('short_description') elsif model.respond_to?('description') # offer keys << model.build_translation_key('description') end end q = 'name:' + keys.join(',') params = PhraseApp::RequestParams::KeysTagParams.new(tags: tags, q: q) records_affected += @client.keys_tag(@project_id, params).first.records_affected end records_affected end def sync_all_translations json = download_locale(Translatable::DEFAULT_LOCALE, true) # compare local keys and remove all remotes that do not exist or are empty locally delete_unused_keys(json) # compare local keys and update differing or create missing remote keys add_missing_or_invalid_keys(json) # simply remove all remote tags delete_all_area_tags # create area tags for all keys tag_all_areas end def delete_unused_keys(json) begin event_ids = json['event'].try(:keys) || [] orga_ids = json['orga'].try(:keys) || [] offer_ids = json['offer'].try(:keys) || [] facet_item_ids = json['facet_item'].try(:keys) || [] navigation_items_ids = json['navigation_item'].try(:keys) || [] keys_to_destroy = get_keys_to_destroy(Orga, orga_ids) + get_keys_to_destroy(Event, event_ids) + get_keys_to_destroy(DataModules::Offer::Offer, offer_ids) + get_keys_to_destroy(DataPlugins::Facet::FacetItem, facet_item_ids) + get_keys_to_destroy(DataModules::FeNavigation::FeNavigationItem, navigation_items_ids) deleted = delete_keys_by_name(keys_to_destroy) Rails.logger.debug "deleted #{deleted} keys." return deleted rescue => exception Rails.logger.error 'error for delete_all_keys_not_used_in_database' Rails.logger.error exception.message Rails.logger.error exception.backtrace.join("\n") raise exception unless Rails.env.production? end end def add_missing_or_invalid_keys(json) updates_json = {} added = 0 model_classes = [ Orga, Event, DataModules::Offer::Offer, DataPlugins::Facet::FacetItem, DataModules::FeNavigation::FeNavigationItem ] model_classes.each do |model_class| model_class.all.each do |model| type = model.class.translation_key_type id = model.id.to_s if ( # model not in json !json[type] || !json[type][id] || # title differs model.title.present? && json[type][id]['title'] != model.title || # short description differs model.respond_to?('short_description') && model.short_description.present? && json[type][id]['short_description'] != model.short_description ) update_json = model.create_json_for_translation_file(only_changes: false) updates_json = updates_json.deep_merge(update_json) added += 1 end end end file = write_translation_upload_json('missing-or-invalid-keys-', updates_json) upload_translation_file_for_locale(file, Translatable::DEFAULT_LOCALE) Rails.logger.info 'finished add_missing_keys' added end def write_translation_upload_json(filename, json) file = Tempfile.new([filename, '.json'], encoding: 'UTF-8') file.write(JSON.pretty_generate(json)) file.close file end private def download_locale(locale, include_empty_translations = false) params = PhraseApp::RequestParams::LocaleDownloadParams.new( file_format: 'nested_json', encoding: 'UTF-8' ) json = @client.locale_download(@project_id, locale, params).force_encoding('UTF-8') return JSON.parse json end def get_keys_to_destroy(model_class, ids) list = [] ids.each do |id| if model = model_class.find_by(id: id) model_class.translatable_attributes.each do |attribute| if model.send(attribute).blank? list << model.build_translation_key(attribute) end end else list << model_class.build_translation_key(id, 'title') if model_class.translatable_attributes.include?(:short_description) list << model_class.build_translation_key(id, 'short_description') end if model_class.translatable_attributes.include?(:description) list << model_class.build_translation_key(id, 'description') end end end list end end
class User < ActiveRecord::Base authenticates_with_sorcery! attr_accessible :username, :email, :role, :password, :password_confirmation validates_confirmation_of :password validates_presence_of :password, :on => :create validates_presence_of :email validates_uniqueness_of :email belongs_to :role def role?(rolename) role.rolename == rolename end end
# == Schema Information # # Table name: tmks # # id :integer not null, primary key # with_who_id :integer not null # from_who_id :integer not null # event_id :integer not null # contact_date :datetime # contact_type :string(255) # notes :text # created_at :datetime # updated_at :datetime # class Tmk < ApplicationRecord belongs_to :with_who, class_name: 'Person', foreign_key: 'with_who_id' belongs_to :from_who, class_name: 'Person', foreign_key: 'from_who_id' belongs_to :event CONTACT_TYPES = %w(Telefônico Pessoal Email) validates_inclusion_of :contact_type, in: CONTACT_TYPES, allow_nil: true, allow_blank: true validates_presence_of :with_who, :from_who, :event def to_s "Tmk/#{with_who.name}" end def self.text_search(query) if query.present? joins('LEFT JOIN people ON people.id = tmks.with_who_id OR people.id = tmks.from_who_id'). joins('LEFT JOIN events ON events.id = tmks.event_id'). where('people.name ilike :q OR contact_type ilike :q OR events.name ilike :q OR notes ilike :q', q: "%#{query}%").references(:people, :events).group('tmks.id') else joins(:with_who, :event).all end end end
Pod::Spec.new do |s| s.name = "CatDetailViewController" s.version = "0.4.0" s.summary = "A way to keep your viewcontroller code compact." s.homepage = "https://github.com/K-cat/CatDetailViewController" s.license = "MIT" s.author = { "K-cat" => "kcatismyname@icloud.com" } s.ios.deployment_target = "5.0" s.source = { :git => "https://github.com/K-cat/CatDetailViewController.git", :tag => "#{s.version}" } s.source_files = "CatDetailViewController/CatDetailViewController/*.{h,m,plist}" s.frameworks = "UIKit" s.requires_arc = true end
class Particle3D attr_accessor :x, :y, :z, :v, :theta, :phi V = 0.03 # x = r sen theta cos phi # y = r sen theta sen phi # z = r cos theta def initialize(x, y, z, theta = nil, phi = nil) set_coords(x, y, z) self.v = V self.theta = theta self.phi = phi self.theta = Random.rand(0..(Math::PI)) unless self.theta self.phi = Random.rand(0..(2 * Math::PI)) unless self.phi end def set_coords(x, y, z) self.x = x % W self.y = y % H self.z = z % D end def move(t) set_coords(x + vx * t, y + vy * t, z + vz * t) end def distance(p) Math.sqrt((x - p.x) ** 2 + (y - p.y) ** 2 + (z - p.z) ** 2) end def alter(neighbors) self.theta = alter_field(neighbors, 'theta', Math::PI) self.phi = alter_field(neighbors, 'phi', 2 * Math::PI) end def alter_field(neighbors, field, max) sin_sum = neighbors.reduce(Math.sin(self.send(field))) { |a, e| a + Math.sin(e.send(field)) } sin_avg = sin_sum.to_f / (neighbors.size + 1) cos_sum = neighbors.reduce(Math.cos(self.send(field))) { |a, e| a + Math.cos(e.send(field)) } cos_avg = cos_sum.to_f / (neighbors.size + 1) noise = Random.rand((-ETA / 2)..(ETA / 2)) avg = Math.atan(sin_avg / cos_avg) (avg + noise) % max end def vx v * Math.sin(theta) * Math.cos(phi) end def vy v * Math.sin(theta) * Math.sin(phi) end def vz v * Math.cos(theta) end def v_mod Math.sqrt(vx ** 2 + vy ** 2 + vz ** 2) end def red ((vx / V) + 0.5) / 1.5 end def green ((vy / V) + 0.5) / 1.5 end def blue ((vz / V) + 0.5) / 1.5 end end
require "application_system_test_case" class Laba11sTest < ApplicationSystemTestCase setup do @laba11 = laba11s(:one) end test "visiting the index" do visit laba11s_url assert_selector "h1", text: "Laba11s" end test "creating a Laba11" do visit laba11s_url click_on "New Laba11" click_on "Create Laba11" assert_text "Laba11 was successfully created" click_on "Back" end test "updating a Laba11" do visit laba11s_url click_on "Edit", match: :first click_on "Update Laba11" assert_text "Laba11 was successfully updated" click_on "Back" end test "destroying a Laba11" do visit laba11s_url page.accept_confirm do click_on "Destroy", match: :first end assert_text "Laba11 was successfully destroyed" end end
require 'spec_helper' describe SendRecommendation do let(:user) { create :user } let(:target) { create :place } let(:receiver_email) { Faker::Internet.email } context 'for follow recommendations' do let(:params) { { target: target, email: receiver_email, user: user, kind: :follow } } subject { SendRecommendation.new(params).call } it 'creates a recommendation instance' do expect{ subject }.to change(Recommendation, :count).by 1 end it 'returns the recommendation' do expect(subject).to be_an_instance_of Recommendation end it 'sets the sent_at timestamp on the recommendation' do expect(subject.reload.sent_at).to_not be_nil end it 'sets the receiver user to the recommendation if it can find one' do receiver = create(:user) params[:email] = receiver.email expect(subject.receiver).to eq receiver end it 'sends a follow recommendation notification' do expect{ subject }.to send_notification(:follow_recommendation) end context 'if an error is raised during the process' do before { DatabaseCleaner.strategy = :truncation } after { DatabaseCleaner.strategy = :transaction } before { allow_any_instance_of(RecommendationReceiver).to receive(:notify) { raise 'Foo' } } it 'rolls back the creation of the recommendation' do pre_count = Recommendation.count expect{ subject }.to raise_error expect(Recommendation.count).to eq pre_count end end context 'with a persona option' do before { params[:persona] = "foo" } it 'saves the persona value to the recommendation' do expect(subject.persona).to eq "foo" end end end end
Then /^it is necessary that the deadline be later than the current date$/ do current_date = Time.now.year.to_s + "-" + Time.now.month.to_s + "-" + Time.now.day.to_s Project.first.deadline.should > current_date.to_date end
class SpecialtiesController < ApplicationController def index request.format = "json" @specialties = Specialty.all respond_to do |format| format.json { render json: @specialties} end end end
module CsvRowModel module CheckOptions extend ActiveSupport::Concern class_methods do def check_options(*klasses) options = klasses.extract_options! valid_options = klasses.map {|klass| klass.try(:valid_options) }.compact.flatten invalid_options = options.keys - valid_options raise ArgumentError.new("Invalid option(s): #{invalid_options}") if invalid_options.present? klasses.each { |klass| klass.try(:custom_check_options, options) } true end end end end