text
stringlengths
10
2.61M
FactoryGirl.define do factory :team, class: Wildcat::Team do id { SecureRandom.random_number(1e2.to_i) } name { ["Baltimore Ravens", "Carolina Panthers"].sample } nickname { name.split(' ').last } abbreviation { ["BAL", "CAR"].sample } location { "#{Forgery(:address).city}, #{Forgery(:address).state_abbrev}" } conference { %w(AFC NFC).sample } division { %w(North South East West).sample } end factory :game, class: Wildcat::Game do id { SecureRandom.random_number(1e3.to_i) } label { "Ravens at Panthers" } season { Forgery(:date).year } stadium { "Bank of America Stadium" } week { (1..17).to_a.sample } home_team_id { SecureRandom.random_number(1e2.to_i) } away_team_id { SecureRandom.random_number(1e2.to_i) } played_at { Time.now } end end
# A cache store implementation which stores everything into memory in the # same process. If you're running multiple Ruby on Rails server processes # (which is the case if you're using mongrel_cluster or Phusion Passenger), # then this means that your Rails server process instances won't be able # to share cache data with each other. # # EnhancedMemoryStore extends the default Rails MemoryStore, adding # the :expires_in option, so that it is compatible with the # MemCacheStore. It stores values in a nested hash, like so: # { :value => value, :expires_at => expiry_timestamp } # # EnhancedMemoryStore is not only able to store strings, but also # arbitrary Ruby objects. # # EnhancedMemoryStore is not thread-safe. Use SynchronizedMemoryStore instead # if you need thread-safety. module ActiveSupport module Cache class EnhancedMemoryStore < MemoryStore # Reads a value from the cache. # # If the entry has expired, it will be purged. def read(name, options = nil) wrapper = super(name, options) if wrapper && wrapper.kind_of?(Hash) if wrapper[:expires_at] if wrapper[:expires_at] > Time.now # fresh wrapper[:value] else # stale delete(name) nil end else # no expiry wrapper[:value] end else # no wrapper; return raw result wrapper end end # Writes a value to the cache. # # Possible options: # - +:unless_exist+ - set to true if you don't want to update the cache # if the key is already set. # - +:expires_in+ - the number of seconds that this value may stay in # the cache. See ActiveSupport::Cache::Store#write for an example. def write(name, value, options = nil) # check :unless_exist option return nil if options && options[:unless_exist] && exist?(name) # create wrapper with expiry data wrapper = if options && options[:expires_in] { :value => value, :expires_at => expires_in(options).from_now } else { :value => value } end # call ActiveSupport::Cache::MemoryStore#write super(name, wrapper, options) end end end end
When("I hover over the main Image") do @PdpNina.zoom_mouse_image end Then("I should see the zoomed image pop up") do @PdpNina.zoom_mouse_image expect(page).to have_content(@PdpNina.getZoomedImg) end When("I Click the blue arrow in the Specifications section") do @PdpNina.clickExpandSpecifications sleep 2 end Then("I should see the Combo Product's Specifications section expanded") do expect(page).to have_content(@PdpNina.getSpecs) end When("I click on Add To my Lists Button") do @PdpNina.clickAddToMyListsButton sleep 3 end Then("I should see the Add To My Lists modal") do expect(page).to have_content(@PdpNina.getListModal) end When("I click on the View All link") do @PdpNina.clickEntireCollectionViewAll sleep 2 end Then("I should see the collection page") do expect(page).to have_text("PROFLO®") end When("I click on the first Checkbox on the Frequently Purchased Together section") do @PdpNina.clickCheckBox sleep 1 end When("I click the checkbox again") do @PdpNina.clickCheckBox sleep 1 end Then("I should see the all checkboxes active") do expect(page).to have_content(@PdpNina.getActiveBox) end When("I click on the Add to Cart button in the Frequently Purchased Together section") do @PdpNina.clickFPTAddToCartButton @PdpNina.goToCart end Then("I should see the cart page") do expect(page).to have_text("SHOPPING CART") end Then("I should see all the products from the FTP version added to cart") do expect(page).to have_text("PF1400TWH") expect(page).to have_text("3519954") expect(page).to have_text("PF5112HEWH") expect(page).to have_text("PFTSEC1000WH") end When("I click on the Right-side arrow in the Entire collection section") do @PdpNina.clickArrowRight sleep 1 end Then("I should see the products shift") do expect(page).to have_content(@PdpNina.getEntireCollection) end When("I click on the Left-side arrow in the Entire collection section") do @PdpNina.clickArrowLeft sleep 1 end When("I click on a color option for the product") do @PdpNina.clickSecondColor sleep 2 end Then("I should see the product change to the color variant selected") do expect(page).to have_text("M6190BL") expect(page).to have_text("Matte Black") end When("I click on the Add to Cart Button") do @PdpNina.clickAddToCartButton sleep 1 end Then("I should see a brief with the Checkout Now link") do expect(page).to have_text("item(s) added to Cart Checkout Now") expect(page).to have_link("Checkout Now", :href => "https://www.ferguson.com/shoppingCart") end Then("I should see the product in the Cart Page") do @PdpNina.goToCart expect(page).to have_text("SHOPPING CART") expect(page).to have_content(@PdpNina.getOrderSummary) expect(page).to have_text("PF1400TWH") end When("I Click the Check other stores link") do @PdpNina.clickCheckStores sleep 3 end Then("I should see the store modal") do expect(page).to have_content(@PdpNina.getStoreModal) end When("I Click the See Whats Available link") do @PdpNina.clickCheckAvailability sleep 3 end Then("I should see the availability modal") do expect(page).to have_content(@PdpNina.getStoreModal) end Then("I should see the Color Product's Specifications section expanded") do expect(page).to have_content(@PdpNina.getSpecs) end When("I click the print button") do @PdpNina.clickPrint end Then("I should see the print preview popup") do pending # Write code here that turns the phrase above into concrete actions end When("I click on a Size option for the product") do @PdpNina.clickBuyingOptionsLink sleep 2 end Then("I should see the product change to the Size variant selected") do expect(page).to have_text("DMJLSLA10") end When("I Click the Check other stores link in the size option tab") do @PdpNina.clickBuyingOptionsLink @PdpNina.clickSizeAvailabilitylink sleep 2 end When("I Click the See Whats Available link in the size option tab") do @PdpNina.clickBuyingOptionsLink @PdpNina.clickSizeShippingLink sleep 2 end Then("I should see the Size Product's Specifications section expanded") do expect(page).to have_content(@PdpNina.getSizeOptionsExpanded) end When("I click on Add To my Lists Button in the size option tab") do @PdpNina.clickBuyingOptionsLink @PdpNina.clickSizeListBtn sleep 2 end When("I click on the Add to Cart Button in the size option tab") do @PdpNina.clickBuyingOptionsLink @PdpNina.clickSizeCartBtn sleep 2 end Then("I should see the Color product in the Cart Page") do @PdpNina.goToCart expect(page).to have_text("SHOPPING CART") expect(page).to have_content(@PdpNina.getOrderSummary) expect(page).to have_text("P6190") end Then("I should see the Size product in the Cart Page") do @PdpNina.goToCart expect(page).to have_text("SHOPPING CART") expect(page).to have_content(@PdpNina.getOrderSummary) expect(page).to have_text("DMJLSLA") end When("I click on the second image") do @PdpNina.clickSecondImage sleep 3 @PdpNina.zoom_mouse_image end Then("I should see the second image show up in the zoom container") do @PdpNina.zoom_mouse_image expect(page).to have_content(@PdpNina.getZoomedImg) end
require "./ratio" require "./parser" begin if ARGV[0]==nil raise "Error" end s=ARGV[0] print(Parser.new(s).parse().to_str) rescue => error print("Error") end
# frozen_string_literal: true # A set of transformations that can be applied to a blob to create a variant. This class is exposed via # the ActiveStorage::Blob#variant method and should rarely be used directly. # # In case you do need to use this directly, it's instantiated using a hash of transformations where # the key is the command and the value is the arguments. Example: # # ActiveStorage::Variation.new(resize: "100x100", monochrome: true, trim: true, rotate: "-90") # # A list of all possible transformations is available at https://www.imagemagick.org/script/mogrify.php. class ActiveStorage::Variation attr_reader :transformations class << self # Returns a Variation instance based on the given variator. If the variator is a Variation, it is # returned unmodified. If it is a String, it is passed to ActiveStorage::Variation.decode. Otherwise, # it is assumed to be a transformations Hash and is passed directly to the constructor. def wrap(variator) case variator when self variator when String decode variator else new variator end end # Returns a Variation instance with the transformations that were encoded by +encode+. def decode(key) new ActiveStorage.verifier.verify(key, purpose: :variation) end # Returns a signed key for the +transformations+, which can be used to refer to a specific # variation in a URL or combined key (like <tt>ActiveStorage::Variant#key</tt>). def encode(transformations) ActiveStorage.verifier.generate(transformations, purpose: :variation) end end def initialize(transformations) @transformations = transformations end # Accepts an open MiniMagick image instance, like what's returned by <tt>MiniMagick::Image.read(io)</tt>, # and performs the +transformations+ against it. The transformed image instance is then returned. def transform(image) transformations.each do |name, argument_or_subtransformations| image.mogrify do |command| if name.to_s == "combine_options" argument_or_subtransformations.each do |subtransformation_name, subtransformation_argument| pass_transform_argument(command, subtransformation_name, subtransformation_argument) end else pass_transform_argument(command, name, argument_or_subtransformations) end end end end # Returns a signed key for all the +transformations+ that this variation was instantiated with. def key self.class.encode(transformations) end private def pass_transform_argument(command, method, argument) if eligible_argument?(argument) command.public_send(method, argument) else command.public_send(method) end end def eligible_argument?(argument) argument.present? && argument != true end end
class Admin::ContactsController < Admin::AdminController # GET /article_categories # GET /article_categories.json def index @contacts = Contact.paginate(:page => params[:page]).order('id') end # GET /article_categories/1 # GET /article_categories/1.json def show @contact = Contact.find(params[:id]) end # DELETE /article_categories/1 # DELETE /article_categories/1.json def destroy @contact = Contact.find(params[:id]) @contact.destroy respond_to do |format| format.html { redirect_to admin_contacts_url } end end end
module OrderConcern extend ActiveSupport::Concern include ApplicationConcern include StateNameConcern attr_reader :order_id, :store, :products, :address, :client, :address, :marketplace, :order_params, :auth_token, :seller_id Address = Struct.new(:name, :line_1, :line_2, :line_3, :city, :state_or_province_code, :country_code, :postal_code) Item = Struct.new(:seller_sku, :seller_fulfillment_order_item_id, :quantity) ORDER_STATUS = [{id: 0, status: "incomplete"}, {id: 1, status: "pending"}, {id: 2, status: "shipped"}, {id: 3, status: "partially shipped"}, {id: 4, status: "refunded"}, {id: 5, status: "cancelled"}, {id: 6, status: "declined"}, {id: 7, status: "awaiting payment"}, {id: 8, status: "awaiting pickup"}, {id: 9, status: "awaiting shipment"}, {id: 10, status: "completed"}, {id: 11, status: "awaiting fulfillment"}, {id: 12, status: "manual verification required"},{id: 13, status: "disputed"}, {id: 14, status: "partially refunded"}] def what_to_do_with_order(order_params, store, products, address) @order_params = order_params @store = store @products = products @address = address setup_amazon_client new_order_or_update end def find_bc_order_in_db Order.find_by(store_id: store.id, bc_order_id: order_params["data"]["id"]) end def new_order_or_update order = find_bc_order_in_db @order_id = order_params["data"]["id"] if order.nil? Order.create(bc_order_id: @order_id, amazon_order_id: @order_id, store_id: store.id, order_status: return_bc_status, fulfillable: true) send_bc_order_to_amazon else status = return_bc_status order.update(order_status: status) if does_order_exist_at_amazon?(order) cancel_on_amazon_if_needed(status, order) end end end def does_order_exist_at_amazon?(order) does_order_exist = false begin client.get_fulfillment_order(order.amazon_order_id) rescue StandardError => e Rails.logger.info "\n nope, doesn't look like the order exists at Amazon, this is the order #{order} and the message from amazon #{e}\n" else does_order_exist = true end return does_order_exist end def cancel_on_amazon_if_needed(status, order) if status == "cancelled" begin amazon_order = client.get_fulfillment_order(order.amazon_order_id).parse rescue StandardError => e Rails.logger.info "Order id #{order.amazon_order_id} from user #{seller_id} failed because of #{e}" else cancel_on_amazon_if_not_canceled_before(amazon_order, order_id) end end end def cancel_on_amazon_if_not_canceled_before(amazon_order, order_id) amazon_order_status = amazon_order["FulfillmentOrder"]["FulfillmentOrderStatus"] unless amazon_order_status == "CANCELLED" client.cancel_fulfillment_order(order_id) end end def return_bc_status id = order_params["data"]["status"]["new_status_id"] bc_order_status = "" ORDER_STATUS.each do |status| if status.has_value?(id) bc_order_status = status[:status] end end return bc_order_status end def send_bc_order_to_amazon #NOT SURE IF THIS IS RIGHT! I'm only sending orders with a status of 11 to amazon. order_status_id = order_params[:data][:status][:new_status_id] if order_status_id == 11 @address = address[0] create_amazon_order end end def setup_amazon_client @marketplace ||= store.amazon.marketplace @seller_id ||= store.amazon.seller_id @auth_token ||= store.amazon.auth_token @client ||= create_amazon_client(@marketplace, @seller_id, @auth_token) end def create_amazon_order db_order = Order.find_by(store_id: store.id, bc_order_id: get_bc_order_id) begin client.create_fulfillment_order( get_bc_order_id, get_bc_order_id, Time.now.getutc, "Thank You", get_shipping_speed(address), create_amazon_shipping_address, create_amazon_skus, opts = {marketplace_id: store.amazon.marketplace}) rescue StandardError => e db_order.update(order_status: "send to amazon failed because of #{e}") Rails.logger.info "\n This order got messed up! bc_order_id is : #{get_bc_order_id} and this happened: #{e}" else db_order.update(order_status: "sent to amazon", sent_to_amazon: true) end end def get_bc_order_id @order_id ||= address[:order_id] end def get_shipping_speed(address) shipping_method = address.shipping_method shipping_method.scan(/\(([^\)]+)\)/).first.first end def create_amazon_shipping_address first_name = address[:first_name] last_name = address[:last_name] name = [first_name, last_name].join(' ') line_1 = address[:street_1] line_2 = address[:street_2] city = address[:city] state = convert_state_name_to_code(address[:state]) country_code = address[:country_iso2] zip = address[:zip] Address.new(name, line_1, line_2, "", city, state, country_code, zip) end def create_amazon_skus skus = [] products.each do |item| item_id = 3.times.map { [*'0'..'9', *'a'..'z'].sample }.join skus << Item.new(item.sku, item_id, item.quantity) end return skus end end
# frozen_string_literal: true require 'spec_helper' RSpec.describe Brcobranca::Retorno::RetornoCnab400 do before do @arquivo = File.join(File.dirname(__FILE__), '..', '..', 'arquivos', 'CNAB400.RET') end it 'Ignora primeira linha que é header' do pagamentos = described_class.load_lines(@arquivo) pagamento = pagamentos.first expect(pagamento.sequencial).to eql('000002') end it 'Transforma arquivo de retorno em objetos de retorno retornando somente as linhas de pagamentos de títulos sem registro' do pagamentos = described_class.load_lines(@arquivo) expect(pagamentos.size).to eq(53) # deve ignorar a primeira linha que é header pagamento = pagamentos.first expect(pagamento.agencia_com_dv).to eql('0730') expect(pagamento.cedente_com_dv).to eql('035110') expect(pagamento.nosso_numero).to eql('00000011') expect(pagamento.carteira_variacao).to eql('109') expect(pagamento.carteira).to eql('I') expect(pagamento.data_vencimento).to eql('000000') expect(pagamento.valor_titulo).to eql('0000000004000') expect(pagamento.banco_recebedor).to eql('104') expect(pagamento.agencia_recebedora_com_dv).to eql('18739') expect(pagamento.especie_documento).to eql('') expect(pagamento.valor_tarifa).to eql('0000000000210') expect(pagamento.iof).to eql('0000000000000') expect(pagamento.valor_abatimento).to eql('0000000000000') expect(pagamento.desconto).to eql('0000000000000') expect(pagamento.valor_recebido).to eql('0000000003790') expect(pagamento.juros_mora).to eql('0000000000000') expect(pagamento.outros_recebimento).to eql('0000000000000') expect(pagamento.data_credito).to eql('210513') expect(pagamento.motivo_ocorrencia).to eql([]) expect(pagamento.sequencial).to eql('000002') # Campos da classe base que não encontrei a relação com CNAB400 # parse.field :tipo_cobranca,80..80 # parse.field :tipo_cobranca_anterior,81..81 # parse.field :natureza_recebimento,86..87 # parse.field :convenio,31..37 # parse.field :comando,108..109 # parse.field :juros_desconto,201..213 # parse.field :iof_desconto,214..226 # parse.field :desconto_concedito,240..252 # parse.field :outras_despesas,279..291 # parse.field :abatimento_nao_aproveitado,292..304 # parse.field :data_liquidacao,295..300 # parse.field :valor_lancamento,305..317 # parse.field :indicativo_lancamento,318..318 # parse.field :indicador_valor,319..319 # parse.field :valor_ajuste,320..331 end end
class CreateFieldValues < ActiveRecord::Migration def change create_table :field_values do |t| t.string :value t.string :field_api_name, null: false t.integer :structure_id, null: false t.timestamps end add_foreign_key :field_values, :structures, on_delete: :cascade add_index :field_values, [:field_api_name, :structure_id], unique: true end end
class StarsController < ApplicationController expose(:webinar) { Webinar.find(webinar_params[:webinar_id]) } expose(:star) def create star.user_id = current_user.id star.webinar_id = webinar.id if star.save redirect_to webinars_path else redirect_to webinars_path, error: I18n.t('controllers.star.create.error') end end def destroy star.destroy if star.destroyed? redirect_to webinars_path else redirect_to webinars_path, error: I18n.t('controllers.star.destroy.error') end end private def webinar_params params.permit(:webinar_id) end end
class ChangeWp10DataType < ActiveRecord::Migration def change change_column :revisions, :wp10, :float change_column :revisions, :wp10_previous, :float end end
class HistoricalEvent < ApplicationRecord include Concerns::Images::ValidatesAttachment validates :title, :description, :date, presence: true, uniqueness: true resourcify end
require 'yaml' require 'ostruct' module Warren class << self attr_accessor :config end DEFAULT_CONFIG = { "node_name": "rabbit", "policies": {}, "base_mnesia_dir": '/var/lib/rabbitmq/mnesia', "log_base": '/var/lib/rabbitmq/infos', "log_level": Logger::INFO } def self.reset_config(configuration = OpenStruct.new(DEFAULT_CONFIG)) self.config = configuration.freeze end self.reset_config def self.configure configuration = @config.dup yield(configuration) @config = configuration.freeze end def self.config_file(path) DEFAULT_CONFIG.merge(YAML::load_file(path)) end end
#payload json.user do json.partial! "./api/users/user", user: @user end json.tickets do @user.tickets.each do |ticket| json.set! ticket.id do #object of event names for which user registered json.extract! ticket, :id, :name, :description, :date, :time, :price, :capacity json.photoUrl url_for(ticket.photo) end end end
require 'spec_helper' describe User do describe '.find_or_create_by_omniauth' do subject { User.find_or_create_by_omniauth(auth) } let(:auth) do { 'provider' => 'twitter', 'uid' => 'uid', 'info' => { 'name' => 'name' }, 'credentials' => { 'token' => 'token', 'secret' => 'secret' } } end context 'find' do before { create :user, :provider => 'twitter', :uid => 'uid', :name => 'name' } it { should_not be_a_new(User) } its(:provider) { should eq 'twitter' } its(:uid) { should eq 'uid' } its(:name) { should eq 'name' } end context 'create' do it { should_not be_a_new(User) } its(:provider) { should eq 'twitter' } its(:uid) { should eq 'uid' } its(:name) { should eq 'name' } its(:token) { should eq 'token' } its(:secret) { should eq 'secret' } end end end
require 'integration_test_helper' class SpecialistSectorBrowsingTest < ActionDispatch::IntegrationTest should "render an specialist sector tag page and list its sub-categories" do subcategories = [ { slug: "oil-and-gas/wells", title: "Wells", description: "Wells, wells, wells." }, { slug: "oil-and-gas/fields", title: "Fields", description: "Fields, fields, fields." }, { slug: "oil-and-gas/offshore", title: "Offshore", description: "Information about offshore oil and gas." }, ] content_api_has_tag("specialist_sector", { slug: "oil-and-gas", title: "Oil and gas", description: "Guidance for the oil and gas industry" }) content_api_has_child_tags("specialist_sector", "oil-and-gas", subcategories) visit "/oil-and-gas" assert page.has_title?("Oil and gas - GOV.UK") within "header.page-header" do assert page.has_content?("Oil and gas") end within ".category-description" do assert page.has_content?("Guidance for the oil and gas industry") end within ".topics ul" do within "li:nth-child(1)" do assert page.has_link?("Wells") end within "li:nth-child(2)" do assert page.has_link?("Fields") end within "li:nth-child(3)" do assert page.has_link?("Offshore") end end end should "render an specialist sector sub-category and its artefacts in groups" do grouped_artefacts = { "Services" => [ "wealth-in-the-oil-and-gas-sector" ], "Guidance" => [ "guidance-on-wellington-boot-regulations" ], "Statistics" => [ "a-history-of-george-orwell" ] } content_api_has_tag("specialist_sector", { slug: "oil-and-gas/wells", title: "Wells", description: "Wells, wells, wells." }, "oil-and-gas") content_api_has_grouped_artefacts_with_a_tag("specialist_sector", "oil-and-gas/wells", "format", grouped_artefacts) visit "/oil-and-gas/wells" assert page.has_title?("Oil and gas: Wells - GOV.UK") within "header.page-header" do assert page.has_content?("Oil and gas") assert page.has_content?("Wells") end within ".services ul" do assert page.has_selector?("li", text: "Wealth in the oil and gas sector") end within ".guidance ul" do assert page.has_selector?("li", text: "Guidance on wellington boot regulations") end within ".statistics ul" do assert page.has_selector?("li", text: "A history of george orwell") end end end
class Post < ApplicationRecord belongs_to :user has_one :movie, as: :videoble accepts_nested_attributes_for :movie end
class AddTaraToAccount < ActiveRecord::Migration def change add_column :accounts, :tara, :string end end
# n method first # input - one 3-letter string representing a codon # output - one string representing the amino acid that corresponds to the given # codon OR an InvalidCodonError # rules: # explicit requirements # each of the 17 codons corresponds to an amino acid OR to STOP # if a STOP codon is reached, we terminate translation # raise InvalidCodonError if the given string is not all codons # mental model: # # a CODON_TO_AMINO_ACID hash # #class InvalidCodonError < RuntimeError; end # #class Translation # CODON_TO_AMINO_ACID = { # 'AUG' => 'Methionine', # 'UUU' => 'Phenylalanine', # 'UUC' => 'Phenylalanine', # 'UUA' => 'Leucine', # 'UUG' => 'Leucine', # 'UCU' => 'Serine', # 'UCC' => 'Serine', # 'UCA' => 'Serine', # 'UCG' => 'Serine', # 'UAU' => 'Tyrosine', # 'UAC' => 'Tyrosine', # 'UGU' => 'Cysteine', # 'UGC' => 'Cysteine', # 'UGG' => 'Tryptophan', # 'UAA' => 'STOP', # 'UAG' => 'STOP', # 'UGA' => 'STOP' # } # # def self.of_codon(codon) # raise InvalidCodonError unless CODON_TO_AMINO_ACID[codon] # CODON_TO_AMINO_ACID[codon] # end # # def self.of_rna(strand) # amino_acids = [] # codons = strand.scan(/[UAGC]{3}/) # raise InvalidCodonError if codons.empty? # # codons.each do |codon| # return amino_acids if of_codon(codon) == 'STOP' # amino_acids << of_codon(codon) # end # # amino_acids # end #end #class InvalidCodonError < RuntimeError; end # #class Translation # CODON_TO_AMINO_ACID = { # AUG: 'Methionine', # UUU: 'Phenylalanine', # UUC: 'Phenylalanine', # UUA: 'Leucine', # UUG: 'Leucine', # UCU: 'Serine', # UCC: 'Serine', # UCA: 'Serine', # UCG: 'Serine', # UAU: 'Tyrosine', # UAC: 'Tyrosine', # UGU: 'Cysteine', # UGC: 'Cysteine', # UGG: 'Tryptophan', # UAA: 'STOP', # UAG: 'STOP', # UGA: 'STOP' # } # # def self.of_codon(codon) # raise InvalidCodonError unless CODON_TO_AMINO_ACID[codon.to_sym] # CODON_TO_AMINO_ACID[codon.to_sym] # end # # def self.of_rna(strand) # amino_acids = [] # codons = strand.scan(/[UAGC]{3}/).map(&:to_sym) # raise InvalidCodonError if codons.empty? # # codons.each do |codon| # return amino_acids if of_codon(codon) == 'STOP' # amino_acids << of_codon(codon) # end # # amino_acids # end #end class InvalidCodonError < ArgumentError; end class Translation CODON_TO_AMINO_ACID = { 'AUG' => 'Methionine', 'UUU' => 'Phenylalanine', 'UUC' => 'Phenylalanine', 'UUA' => 'Leucine', 'UUG' => 'Leucine', 'UCU' => 'Serine', 'UCC' => 'Serine', 'UCA' => 'Serine', 'UCG' => 'Serine', 'UAU' => 'Tyrosine', 'UAC' => 'Tyrosine', 'UGU' => 'Cysteine', 'UGC' => 'Cysteine', 'UGG' => 'Tryptophan', 'UAA' => 'STOP', 'UAG' => 'STOP', 'UGA' => 'STOP' }.freeze def self.of_codon(codon) CODON_TO_AMINO_ACID.fetch(codon) { raise InvalidCodonError } end def self.of_rna(strand) strand.scan(/.../).each_with_object([]) do |codon, amino_acids| return amino_acids if of_codon(codon) == 'STOP' amino_acids << of_codon(codon) end end end
require 'digest/sha2' class User < ActiveRecord::Base # An user have many rooms has_many :rooms # oAuth has_many :client_applications has_many :tokens, :class_name => "OauthToken", :order => "authorized_at desc", :include => [:client_application] attr_accessor :password, :password_confirmation validates :password, :presence => true, :confirmation => true, :on => :create # :length => { :within => 6..40 } validates :email, :uniqueness => true, :presence => true, :format => { :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i } #validates_uniqueness_of :email before_save :hash_new_password, :if => :password_changed? def password_changed? !@password.blank? end def has_password?(submitted_password) hashed_password == Digest::SHA2.hexdigest(salt + submitted_password) end def credit=(credit) self[:credit] = (credit*100).to_i end def credit (self[:credit].to_f)/100 end def self.authenticate(email, submitted_password) user = find_by_email(email) return nil if user.nil? return user if user.has_password?(submitted_password) end def self.authenticate_with_salt(id, cookie_salt) user = find_by_id(id) (user && user.salt == cookie_salt) ? user : nil end private def hash_new_password self.salt = ActiveSupport::SecureRandom.base64(8) self.hashed_password = Digest::SHA2.hexdigest(self.salt + @password) end end
# frozen_string_literal: true require 'digest/md5' require 'param/secure_auth_header' require 'param/simple_auth_header' module Uploadcare module Param # This object returns headers needed for authentication # This authentication method is more secure, but more tedious class AuthenticationHeader # @see https://uploadcare.com/docs/api_reference/rest/requests_auth/#auth-uploadcare def self.call(options = {}) case Uploadcare.config.auth_type when 'Uploadcare' SecureAuthHeader.call(options) when 'Uploadcare.Simple' SimpleAuthHeader.call else raise ArgumentError, "Unknown auth_scheme: '#{Uploadcare.config.auth_type}'" end end end end end
require 'bots/my_bot/contact' require 'bots/my_bot/detector' class Hostiles < Array def initialize(tank) @tank = tank end def <<(contact) contact = update(contact) contact ? super(contact) : self end def closest sort.find { |contact| !contact.lost?(time) } end def find(target) target && super() { |contact| contact == target } end def push(contact) contact = update(contact) contact ? super(contact) : self end def unshift(contact) contact = update(contact) contact ? super(contact) : self end private attr_reader :tank #def bearing # tank.radar_heading #end def convert(object) if object.respond_to?(:name) && object.name == tank.name nil elsif object.is_a?(RTanque::Bot::Radar::Reflection) Contact.new(object, Detector.new(tank)) elsif object.is_a?(Contect) object else nil end end def time tank.time end def update(object) contact = convert(object) known_contact = find(contact) if known_contact known_contact.update(contact) contact = nil end contact end end
class CreateTsServiceDemandBreakdownUsagePatterns < ActiveRecord::Migration def change create_table :ts_service_demand_breakdown_usage_patterns do |t| t.integer :user_id t.references :service_demand_breakdown t.integer :year t.integer :month t.integer :date t.float :quantity t.decimal :revenue t.timestamps end change_table :ts_service_demand_breakdown_usage_patterns do |t| t.index :user_id t.index :service_demand_breakdown_id, :name => 'index_ts_service_demand_breakdown_usage_patterns_on_sdb_id' end end end
AutoStripAttributes::Config.setup do set_filter(upcase_first: false) do |value| !value.blank? && value.respond_to?(:upcase_first) ? value.upcase_first : value end end
class AddPhoneToUsers < ActiveRecord::Migration def change add_column :users, :phone_number, :string add_column :users, :time, :datetime end end
module RPG #============================================================================== # ** RPG::EquippableItem #--------------------------------------------------------------------------- # Inserisce gli attributi appropiati agli oggetti equipaggiabili #============================================================================== class Weapon < BaseItem include ExtraAttr def cri @cri + (@critical_bonus ? 4 : 0) end def hit @hit - 95 end # determina se l'arma cambia il tipo di supporto def changes_support_type? @use_support != nil end def has_placeholder? false end def is_placeholder? false end def priority 4 end def ranged? quality?(:ranged) end end #equippableitem #============================================================================== # ** RPG::Armor #--------------------------------------------------------------------------- # Inserisce gli attributi appropiati agli oggetti equipaggiabili #============================================================================== class Armor < BaseItem # in equip overhaul attr_reader :hit attr_reader :cri include ExtraAttr def another_support_type? @kind == 0 and @support_type != nil end def has_placeholder? false end def is_placeholder? @is_placeholder end def priority 3 end end #equippableitem #============================================================================== # ** RPG::State #--------------------------------------------------------------------------- # Inserisce gli attributi appropiati per gli stati alterati #============================================================================== class State attr_reader :description attr_reader :slip_damage_per include ExtraAttr # True se lo status è un buff def buff? @buff_type == :buff end # True se lo status è un debuff def debuff? @buff_type == :debuff end def linked_to_element? @linked_element > 0 end # @return [String] def description @description end def viral? quality? :viral end def bombify? quality? :bombify end # @return [Hash] def stat_per stats = {} [:atk, :spi, :def, :agi, :maxhp, :maxmp, :hit, :eva, :cri, :odds].each do |stat| stats[stat] = stat_bonus(stat) end stats end def stat_bonus(param) if super(param) == 0 and [:atk, :spi, :def, :agi].include?(param) case param when :atk return @atk_rate - 100 when :spi return @spi_rate - 100 when :def return @def_rate - 100 when :agi return @agi_rate - 100 else return 0 end end super(param) end end #state #============================================================================== # ** RPG::Enemy #--------------------------------------------------------------------------- # Inserisce gli attributi appropiati per i nemici #============================================================================== class Enemy attr_reader :description attr_reader :attack_attr attr_reader :use_anger attr_reader :boss_type attr_reader :unprotected include ExtraAttr # restituisce l'attributo principale al danno # @return [RPG::Element_Data, nil] def attack_attribute return nil if @attack_attr.nil? $data_system.weapon_attributes.select { |attr| attr.id == attack_attr }.first end # determina se è un protettore def protector? @protector end def force_show_atb? quality?(:show_atb) end def priority 0 end # @return [TrueClass, FalseClass] def boss_type quality?(:boss_type) end end #============================================================================== # ** RPG::UsableItem #--------------------------------------------------------------------------- # Imposta gli attributi per le abilità #============================================================================== class UsableItem include MultiAttributable attr_reader :esper #esper evocato attr_reader :spirit_stone #spirit_stone attr_reader :absorb_damage_party #assorbi danno e dona al gruppo attr_reader :anger_cost #costo ira attr_reader :anger_rate #carica ira attr_reader :tank_odd #aggro al tank attr_reader :state_inf_bon #bonus probabilità infliggi status attr_reader :state_inf_per #bonus probabilità infliggi status perc. attr_reader :state_inf_dur #bonus durata status attr_reader :ignore_bonus #ignora bonus attr_reader :sk_types #tipo di abilità (per costo) attr_reader :range_type #distanza [0: meele, 1: ranged] attr_reader :buff_steal #flag per rubare i buff attr_reader :debuff_pass #flag per trasferire i debuff al bersaglio attr_reader :reset_damage attr_reader :mp_damage_per #percentuale di danni MP con i danni HP attr_reader :mp_heal_per # percentuale di auto-cura MP con i danni HP attr_reader :required_menu_switch # @return [Autostate_Skill] attr_reader :autostate attr_reader :cri attr_reader :custom_damage_formula attr_reader :critical_condition attr_reader :transfer_aggro attr_reader :clear_anger attr_reader :knockback_rate # eredita i bonus di attacco normale sui danni della skill attr_reader :inherit_normal_atk_bonus # @return [Array] attr_reader :target_states RANGE_TYPE_MEELE = 0 RANGE_TYPE_RANGED = 1 # Inizializza il livello della classe dell'oggetto def load_extra_attr return if @cache_caricata_attr @cache_caricata_attr = true @esper = 0 @absorb_damage_party = false @anger_cost = 0 @spirit_stone = false @ok_with_taumaturgic = false @anger_rate = 0 @tank_odd = 0 @stat_increment = {} @state_inf_bon = 0 @state_inf_per = 0.0 @state_inf_dur = 0 @range_type = nil @ignore_bonus = false @clear_anger = false @sk_types = [] @troop_id = 0 @recharge_skills = false @placeholder_id = 0 @buff_steal = false @debuff_pass = false @reset_damage = false @assimilate = false @assimilable = false @switchable = false @mp_damage_per = 0 @mp_heal_per = 0 @required_menu_switch = 0 @force_on = nil @autostate = nil @target_states = nil @damage_stats = {:spi_f => @spi_f, :atk_f => @atk_f} @critical = true @custom_damage_formula = nil @custom_formula_description = nil @critical_condition = nil @transfer_aggro = false @toggle_type = false @knockback_rate = 0 @cri = 0 @assimilate_data = {} @inherit_normal_atk_bonus = false reading_help = false self.note.split(/[\r\n]+/).each { |row| if reading_help if row =~ ExtraAttr::HELP_END reading_help = false else @description += row end next end next if load_battle_params(row) case row when ExtraAttr::EVOCATION @esper = $1.to_i when ExtraAttr::TAUMATURG @ok_with_taumaturgic = true when ExtraAttr::SPIRITOL @spirit_stone = true when ExtraAttr::PARTY_ABS @absorb_damage_party = true when ExtraAttr::ANGER_COST @anger_cost = $1.to_i when ExtraAttr::ANGER_RATE @anger_rate = $1.to_i when ExtraAttr::TANK_ODDS @tank_odd += $1.to_i when ExtraAttr::STATE_BON @state_inf_bon = $1.to_i when ExtraAttr::ST_BON_PER @state_inf_per += $1.to_f / 100.0 when ExtraAttr::ST_BON_IGN @ignore_bonus = true when ExtraAttr::ST_INF_DUR @state_inf_dur = $1.to_i when ExtraAttr::SK_TYPE_CS @sk_types.push($1) when ExtraAttr::MONSTER_T @troop_id = $1.to_i when ExtraAttr::STAT_INCR @stat_increment[$1] = $2.to_i when ExtraAttr::REC_SKILLS @recharge_skills = true when ExtraAttr::MEELE @range_type = RANGE_TYPE_MEELE when ExtraAttr::RANGED @range_type = RANGE_TYPE_RANGED when ExtraAttr::PLACEHOLDER_ID @placeholder_id = $1.to_i when ExtraAttr::BUFF_STEAL @buff_steal = true when ExtraAttr::DEBUFF_PASS @debuff_pass = true when ExtraAttr::RESET_DAMAGE @reset_damage = true when ExtraAttr::ASSIMILABLE @assimilable = true when ExtraAttr::ASSIMILATE @assimilate = true when ExtraAttr::MAX_ASSIMILABLE @assimilate_data[:max] = $1.to_i when ExtraAttr::ASSIMILATE_ROUNDS @assimilate_data[:rounds] = $1.to_i when ExtraAttr::SKILL_MP_DAMAGE_PER @mp_damage_per = $1.to_f / 100.0 when ExtraAttr::SWITCHABLE @switchable = true when ExtraAttr::MENU_SWITCH @required_menu_switch = $1.to_i when ExtraAttr::HELP_STRT reading_help = true when ExtraAttr::AUTOSTATE_SKILL @autostate = Autostate_Skill.new($1.to_i, $2.to_i) when ExtraAttr::FORCE_ON_TARGET @force_on = $1.to_sym when ExtraAttr::SKILL_MP_HEAL_PER @mp_heal_per = $1.to_f / 100.0 when ExtraAttr::HIT_ALL @scope = 12 # tutti when ExtraAttr::HIT_WITH_STATES @scope = 13 # tutti i nemici che hanno determinati status @target_states = $1.split(/,[ ]*/).map { |id| id.to_i } when ExtraAttr::HIT_OTHERS @scope = 14 when ExtraAttr::CANNOT_CRITICAL @critical = false when ExtraAttr::CRI_RATE @cri = $1.to_i when ExtraAttr::CUSTOM_FORMULA @custom_damage_formula = $1 when ExtraAttr::CUSTOM_F_DESC @custom_formula_description = $1 when ExtraAttr::CRI_CONDITION @critical_condition = $1 when ExtraAttr::ODD_TRANSFER @transfer_aggro = true when ExtraAttr::CLEAR_ANGER @clear_anger = true when ExtraAttr::TOGGLE_TYPE @toggle_type = true when ExtraAttr::KNOCKBACK @knockback_rate = $1.to_f / 100.0 when ExtraAttr::INHERIT_NORMAL_ATK @inherit_normal_atk_bonus = true else nil end } end # determina se ha la qualità # @param [Symbol] quality_sym def has?(quality_sym) if self.class.method_defined?(quality_sym) feature = self.send(quality_sym) if feature.is_a?(Numeric) feature > 0 else feature end else false end end def real_name @name end def effect_same_name? return unless plus_state_set.size == 1 $data_states[plus_state_set.first].real_name == real_name end # restituisce una statistica di danno def damage_stat(stat) return @atk_f if stat == :atk_f return @spi_f if stat == :spi_f @damage_stats[stat] || 0 end # restituisce tutti i calcolatori danno dell'abilità # @return [Array<Symbol>] def involved_damage_stats @damage_stats.keys end # restituisce tutti i sommatori danno # @return [Array<Symbol>] def summation_damage_stats involved_damage_stats.select { |stat| !H87AttrSettings::MULTIPLIERS.include?(stat) } end # restituisce tutti i moltiplicatori danno # @return [Array<Symbol>] def multiplication_damage_stats involved_damage_stats.select { |stat| H87AttrSettings::MULTIPLIERS.include?(stat) } end # carica i parametri custom della formula come agi_f e def_f def load_battle_params(row) H87AttrSettings::FORMULA_CALC_PARAMS.each do |param| if row =~ /<#{param}:?[ ]*(\d+)>/i set_battle_param(param, $1.to_i) return true end end false end def set_battle_param(param, value) @damage_stats[param] = value @atk_f = value if param == :atk_f @spi_f = value if param == :spi_f end # restituice la descrizione della formula del danno # @return [String] def printable_damage_formula return @custom_formula_description if @custom_formula_description != nil return '' if @base_damage == 0 damage = @base_damage.abs components = [] components.push(damage.to_s) if damage > 1 # sempre vero summation_damage_stats.each do |param| value = damage_stat(param) next if value <= 0 next if param == :spi_f and value == 1 if H87AttrSettings::PARAMS_DMG_MULTIPLIERS[param] value *= H87AttrSettings::PARAMS_DMG_MULTIPLIERS[param] end components.push(sprintf('%d%% %s', value, Vocab.param_abbrev(param))) end total = components.join(' + ') components = [] multiplication_damage_stats.each do |param| value = damage_stat(param) next if value <= 0 if H87AttrSettings::PARAMS_DMG_MULTIPLIERS[param] value *= H87AttrSettings::PARAMS_DMG_MULTIPLIERS[param] end components.push(sprintf('%g%% %s', value, Vocab.param_abbrev(param))) end return total if components.empty? (['('+total+')'] + components).join(' x ') end # ottiene il tempo di carica dell'abilità dopo # selezionato il comando nella battaglia. # Si tratta di un attributo per l'ATB. #noinspection RubyResolve def charge_time return 0 if charge.nil? return 0 if charge[1].nil? charge[1] end unless $@ alias h87ff_for_all? for_all? alias h87ff_for_enemy? for_opponent? alias h87ff_for_ally? for_friend? end def for_all? h87ff_for_all? or [12, 13].include? @scope end def for_opponent? h87ff_for_enemy? or [12, 13].include? @scope end def for_friend? h87ff_for_ally? or [12,14].include?(@scope) end def for_all_in_field? @scope == 12 end def for_opponents_with_state? @scope == 13 end def for_other_friends? @scope == 13 end # Restituisce se la skill può essere usata dalla taumaturgia def can_tau? @ok_with_taumaturgic end def toggle_type? @toggle_type and @plus_state_set.size == 1 end # determina se può causare danni critici def can_critical? return false unless @critical return true if physical? H87AttrSettings::CRITICAL_MAGIC end # @return [TrueClass, FalseClass] def critical_condition? @critical_condition != nil end # @return [TrueClass, FalseClass] def custom_formula? @custom_damage_formula != nil end # Restituisce true se la skill ha un certo tipo def type?(type) @sk_types.include?(type) end # Restituisce l'incremento di un determinato parametro # @param [String] stat # @return [Integer] def param_increment(stat) return 0 if @stat_increment[stat].nil? @stat_increment[stat] end # Determina se l'oggetto incrementa un parametro def increases_param? @stat_increment.size > 0 end # Determina se l'oggetto ricarica tutte le skill def skill_recharge? @recharge_skills end # Da definire nelle sottoclassi def meele? !ranged? end def ranged? return false if @scope == 0 return false if for_user? return false unless battle_ok? true end def only_for_domination? @force_on == :domination end def only_for_actor? @force_on == :actor end def heal? @base_damage < 0 end def damaging? @base_damage > 0 end def no_damage? @base_damage == 0 end def hidden_troop? false end end #usable item #============================================================================== # ** RPG::Skill #--------------------------------------------------------------------------- # Classe che contiene le informazioni sulle abilità #============================================================================== class Skill < UsableItem # Riscrittura di menu_ok? def menu_ok? can_tau? ? true : super end # determina se è una skill ravvicinata def meele? return self.range_type == RANGE_TYPE_MEELE if self.range_type != nil return false if (self.element_set & H87AttrSettings::RANGED_ELEMENTS).size > 0 @atk_f > 0 end # determina se è una skill a distanza def ranged? !meele? end def assimilable? @assimilable end def assimilate? @assimilate end def max_assimilable @assimilate_data[:max] end def assimilated_skill_rounds @assimilate_data[:rounds] end # Restituisce il nome dell'abilità #def name # return @name unless @japanese_name # return @name unless japanese_active? # return @japanese_name #end end #============================================================================== # ** RPG::Item #--------------------------------------------------------------------------- # Classe che contiene le informazioni sugli oggetti #============================================================================== class Item < UsableItem attr_reader :troop_id #ID dei mostri attr_reader :placeholder_id # nome dell'oggetto placeholder # determina se l'oggetto ha un placeholder def has_placeholder? @placeholder_id > 0 end # determina se è un equipaggiamento placeholder (inesistente) def is_placeholder? false end # determina se è assimilazione (sempre falso per gli oggetti) def assimilate? false end def hidden_troop? @troop_id > 0 end end class System # determina il rateo di danno quando si equipaggiano due spade def two_swords_damage_rate CPanel::TSWRate end # rateo di danno quando nel party # c'è qualcuno con Altruismo def skill_protect_rate CPanel::PROTECTRATE end end end
class Item < ActiveRecord::Base before_save :create_slug belongs_to :category has_many :descriptions has_many :images has_many :reviews has_many :likes validates :Name, presence: true validates :Description, presence: true accepts_nested_attributes_for :images, :allow_destroy => true accepts_nested_attributes_for :descriptions, :allow_destroy => true accepts_nested_attributes_for :reviews, :allow_destroy => true scope :item_search, -> (query) { joins("LEFT JOIN descriptions ON descriptions.item_id = items.id") .joins("LEFT JOIN images ON images.item_id = items.id") .where("\"Name\" like ? OR \"Description\" like ? OR descriptions.\"Title\" like ? OR descriptions.\"Content\" like ? OR images.\"Title\" like ? OR images.\"Content\" like ?", "%#{query}%","%#{query}%","%#{query}%","%#{query}%","%#{query}%","%#{query}%") .group('items.id') } def create_slug self.slug = self.Name.parameterize end end
# vim: ts=2 sts=2 et sw=2 ft=ruby fileencoding=utf-8 require "spec_helper" describe DMM::Response::Item do before :all do stub_get.to_return(xml_response("com.xml")) @item = DMM::new.item_list.result.items.first end describe 'methods which returns integer' do subject { @item } DMM::Response::Item::KEYS.each do |key| it { should respond_to(key) } end end describe '#large_images' do subject do item = { :sample_image_url => { :sample_s => { :image => ["http://pics.dmm.co.jp/digital/video/aaa00000/aaa00000-9.jpg"], }, } } DMM::Response::Item.new(item) end its(:large_images) { should == ["http://pics.dmm.co.jp/digital/video/aaa00000/aaa00000jp-9.jpg"] } end end
class CreateChartSavedConditions < ActiveRecord::Migration def self.up create_table :chart_saved_conditions do |t| t.string :name, :null => false t.integer :project_id, :null => true t.string :conditions, :null => false t.string :chart, :null => false end add_index :chart_saved_conditions, :project_id end def self.down remove_index :chart_saved_conditions, :project_id drop_table :chart_saved_conditions end end
require 'rails_helper' RSpec.describe PeopleController do describe 'index' do before do request.session[:admin] = true get :index end it do expect(response.status).to eq(200) end it do create :person, name: 'karol' expect(response.body).to match('<li>karol</li>') expect(response.body).to match('<li>jozo</li>') end end describe 'create' do before do post :create, params: { person: { name: "Ezo", address: "Kordiky" }} end it 'should be successful' do expect(response.status).to eq(200) end it 'should create a person' do expect(Person.last.name).to eq 'Ezo' end end end
class Gift < ApplicationRecord belongs_to :user validates :name, :date, :occasion, presence: true end
=begin #Location API #Geolocation, Geocoding and Maps OpenAPI spec version: 2.0.0 Generated by: https://openapi-generator.tech OpenAPI Generator version: 3.3.4 =end require 'date' module unwiredClient class RadioSchema GSM = '\"gsm\"'.freeze UTMS = '\"utms\"'.freeze CDMA = '\"cdma\"'.freeze LTE = '\"lte\"'.freeze # Builds the enum from string # @param [String] The enum value in the form of the string # @return [String] The enum value def build_from_hash(value) constantValues = RadioSchema.constants.select { |c| RadioSchema::const_get(c) == value } raise "Invalid ENUM value #{value} for class #RadioSchema" if constantValues.empty? value end end end
class User < ApplicationRecord has_secure_password has_many :posts, dependent: :destroy has_many :post_requests, dependent: :destroy has_many :transactions, dependent: :destroy has_many :banner_ads, dependent: :destroy has_many :brands, dependent: :destroy has_many :markers, dependent: :destroy has_many :logs, dependent: :destroy has_many :forums, dependent: :destroy has_many :comments, dependent: :destroy has_one :subscription, dependent: :destroy has_many :verify_users, dependent: :destroy has_one_attached :avatar searchkick validates :username, presence: true, :uniqueness => true validates :email, presence: true, :uniqueness => true attr_accessor :old_password, :new_password # scope :sale, -> { where(purpose: "SALE") } # scope :rent, -> { where(purpose: "RENT") } # scope :short, -> { where(purpose: "SHORT") } # scope :development, -> { where(purpose: "NEW") } # scope :installment, -> { where(purpose: "INSTALLMENT") } scope :agents, -> { where.not(account_type: ["PROPERTY_OWNER", "INDIVIDUAL"], company: false) } def self.from_token_request request username = request.params["auth"] && request.params["auth"]["username"] email = request.params["auth"] && request.params["auth"]["email"] user = (self.find_by username: username) || ( self.find_by email: email ) if user && user.authenticate(request.params[:auth][:password]) if user.logs.last user.update_attributes(last_logged_in: user.logs.last.time) else user.update_attributes(last_logged_in: Time.zone.now) end Log.create!( time: Time.zone.now , user_id: user.id ) user.update_attributes(logged_in_at: Time.zone.now) end self.find_by username: username or self.find_by email: email end def self.avatar { resize: "500x500", gravity: 'center', strip: true, 'sampling-factor': '4:2:0', quality: '85', interlace: 'JPEG', colorspace: 'sRGB' } end def to_token_payload { sub: id, email: email, username: username, admin: admin } end def self.check_account_type user account_type = user.account_type case when account_type == "INDIVIDUAL" return false when account_type == "PROPERTY_OWNER" return false else return true end end def subscribed? if self.subscription.plan != "FREE" return true else return false end end end
# Represents a vertex in 3D space class Vertex attr_reader :x, :y, :z def initialize(*v) @x, @y, @z = v end def ==(vertex) x == vertex.x && y == vertex.y && z == vertex.z end end
class UsersController < ApplicationController layout "dashboard" before_action :load_user, only: [:show, :edit, :update] before_action :admin_only, except: [:edit, :update] # GET # Lista todos os usuários def index @users = User.all.page(params[:page]).per_page(10) end # Carrega o usuário e salva seu ID caso seja necessário adicionar # um projeto pertencente ele depois def show session[:user_id] = params[:id] end # GET # Instancia um novo usuário def new @user = User.new end # POST # Gera uma senha aleatória que é atribuída ao usuário # Caso o usuário seja salvo no banco de dados com sucesso, um email é # enviado ao email cadastrado contendo seu login e sua senha def create generated_password = Devise.friendly_token.first(8) @user = User.new(user_params(generated_password)) if @user.save UserMailer.new_user_mail(@user, generated_password).deliver_later redirect_to customers_users_path else render :new end end # GET # Carrega usuário para que seja possível editá-lo def edit end # PATCH # Atualiza os atributos do usuário def update if @user.update_attributes(user_params) redirect_to users_url else render :edit end end # GET # Carrega todos os usuários que não são administradores, ou seja, clientes def customers @users = User.where(admin: false).page(params[:page]).per_page(10) end # GET # Carrega todos os usuários administradores def admins @users = User.where(admin: true).page(params[:page]).per_page(10) end # GET # Instancia um novo usuário # Ao clicar no botão da página, o método chamado será o :create_admin def new_admin @user = User.new end # POST # Método chamado na view da ação :new_admin # Gera uma senha aleatória e a atribui ao usuário. Após isso, o campo # administrador desse usuário é setado para TRUE. # Caso o novo administrador seja salvo com sucesso, um email será # enviado informando-o de seu novo login e senha. def create_admin generated_password = Devise.friendly_token.first(8) @user = User.new(user_params(generated_password)) @user[:admin] = true if @user.save UserMailer.new_user_mail(@user, generated_password).deliver_later redirect_to root_path else render "new" end end # GET # Procura nos usuários e seus relacionados(projetos) pelo(s) termo(s) pesquisado(s) def query query = params[:query] if query.present? @users = User.text_search(query).page(params[:page]).per_page(10) else @users = nil end end private # Carrega usuário a partir do ID def load_user @user = User.find(params[:id]) end # Strong params # A senha é carregada nos parâmetros e então enviada para o usuário para então ser # salvo def user_params(password) params[:user][:password] = password params.require(:user).permit(:username, :name, :contact_name, :phone, :email, :password) end # Checa se o usuário é administrador, caso contrário é levado a raiz do sistema. def admin_only redirect_to root_path, notice: t('alerts.admin_privileges') unless current_user.is_admin? end end
require_relative 'sample_data_macros' module AwardWalletMacros Response = Struct.new(:body) def self.included(base) base.extend ClassMethods base.include SampleDataMacros end def stub_award_wallet_api(json) response = Response.new(json) allow(Integrations::AwardWallet::APIClient).to receive(:get).and_return(response) end def get_award_wallet_user_from_callback(account) result = Integrations::AwardWallet::Callback.( { userId: 12345 }, 'current_account' => account, # don't enqueue a real BG job: 'load_user.job' => double(perform_later: nil), ) raise unless result.success? # sanity check result['model'] end def refresh_award_wallet_user_from_sample_data(user) op = Integrations::AwardWallet::User::Refresh result = op.( { user: user }, 'api' => double(connected_user: parsed_sample_json('award_wallet_user')), ) raise unless result.success? # sanity check result['model'] end # create example AwardWalletUser by mimicking the real flow of operations def setup_award_wallet_user_from_sample_data(account) user = get_award_wallet_user_from_callback(account) result = refresh_award_wallet_user_from_sample_data(user) account.reload result end module ClassMethods def stub_award_wallet_api_key! return if ENV['AWARD_WALLET_API_KEY'] before do @old_api_key = ENV['AWARD_WALLET_API_KEY'] ENV['AWARD_WALLET_API_KEY'] = 'abcdefg' end after { ENV['AWARD_WALLET_API_KEY'] = @old_api_key } end end end
class RemoveItemIdFromDeliveries < ActiveRecord::Migration def up remove_column :deliveries, :item_id end def down add_column :deliveries, :item_id, :integer end end
class CreateRanks < ActiveRecord::Migration def change create_table :ranks do |t| t.integer :rank t.references :mst_date, index: true, foreign_key: true t.references :mst_genre, index: true, foreign_key: true t.references :mst_music, index: true, foreign_key: true t.timestamps null: false end end end
module Spree module Context module Taxon extend ActiveSupport::Concern include Spree::Context::Base included do class_attribute :request_fullpath cattr_accessor :context_routes #(:either, :list,:detail,:cart,:account,:checkout, :thanks,:signup,:login) self.context_routes = { ContextEnum.home =>"/", ContextEnum.account =>"/account", ContextEnum.checkout =>"/checkout", ContextEnum.cart =>"/cart", ContextEnum.signup =>"/signup", ContextEnum.login =>"/login", ContextEnum.either =>"/" #default_taxon for context :either is home } #FIXME what if home is not assigned to theme? def self.home where(:page_context=> 1 ).first end def path context_routes[current_context] || "/#{self.id}" end end # context of default taxon vary in request_fullpath # ex. /cart context is cart # /user context is account # return :either(detail or list), cart, checkout, register, login def current_context # consider query_string d=www.dalianshops.com and preview path /template_themes/2/preview if request_fullpath.present? #for current page, request_fullpath is present case self.request_fullpath when /^\/[\d]+\/[\d]+/ ContextEnum.detail when /^\/cart/ ContextEnum.cart when /^\/user/ ContextEnum.account when /^\/password/ ContextEnum.password when /^\/account/,/users\/[\d]+\/edit/ #users/2/edit ContextEnum.account when /^\/login/, /^\/checkout\/registration/ ContextEnum.login when /^\/signup/ ContextEnum.signup when /^\/checkout/ ContextEnum.checkout when /^\/orders/ ContextEnum.thanks when /^\/signup/ ContextEnum.signup when '/',/^\/\?/, /^\/template_themes/ ContextEnum.home else ContextEnum.list end else case self.page_context when 1 #home ContextEnum.home when 2 #cart ContextEnum.cart when 3 #checkout ContextEnum.checkout when 4 #thanks ContextEnum.thanks when 5 #signup ContextEnum.signup when 6 #login ContextEnum.login when 7 #accout ContextEnum.account else ContextEnum.list end end end def context_either? current_context ==ContextEnum.either end end end end
class ChangeMemberStatusinAccountDetail < ActiveRecord::Migration[5.1] def change remove_column :account_details, :member_status, :string add_column :account_details, :member_status, :integer end end
require "bcrypt" module Castronaut module Adapters module Devise class User < ActiveRecord::Base cattr_accessor :encryptor, :stretches, :pepper def self.authenticate(username, password) if user = find_by_email(username) if user.valid_password?(password) Castronaut::AuthenticationResult.new(username, nil) else Castronaut.config.logger.info "#{self} - Unable to authenticate username #{username} due to invalid authentication information" Castronaut::AuthenticationResult.new(username, "Unable to authenticate") end else Castronaut.config.logger.info "#{self} - Unable to authenticate username #{username} because it could not be found" Castronaut::AuthenticationResult.new(username, "Unable to authenticate") end end def valid_password?(incoming_password) password_digest(incoming_password) == self.encrypted_password end def password_digest(password) self.class.encryptor ||= Bcrypt self.class.stretches ||= 10 self.class.encryptor.digest(password, self.class.stretches , self.password_salt, self.class.pepper ) end end class Bcrypt def self.digest(password, stretches, salt, pepper) ::BCrypt::Engine.hash_secret([password, pepper].join, salt, stretches) end end end end end
class Civilization attr_accessor :name, :unit_settings def initialize(name, unit_settings) @name = name @unit_settings = unit_settings end end
class Detail < ApplicationRecord belongs_to :plan validates :destination, presence: true, length: { maximum: 255 } validates :amount, :numericality => :only_integer validate :start_end_check VALID_PHONE_REGEX = /\A\d{10}$|^\d{11}\z|^\d{0}\z/ validates :phone, format: { with: VALID_PHONE_REGEX } VALID_URL_REGEX = /https:\/\/|http:\/\/|^\d{0}\z/ validates :site_url, format: { with: VALID_URL_REGEX } REGISTRABLE_ATTRIBUTES = %i( name start_at(1i) start_at(2i) start_at(3i) start_at(4i) start_at(5i) stop_at(1i) stop_at(2i) stop_at(3i) stop_at(4i) stop_at(5i) ) private def start_end_check return unless start_at && end_at if start_at >= end_at errors.add(:start_at, 'は終了時間よりも前に設定してください') end end end
json.array!(@homeworks) do |homework| json.extract! homework, :id, :student_id, :class_name, :description, :status json.url homework_url(homework, format: :json) end
# # Gemfile # # Keeping a Gemfile up to date and especially updated Gems with security issues # is an important maintenance task. # # 1) Which Gems are out of date? # 2) Update a Gem # 3) Gemfile.lock # 4) Versioning # 5) Importance of a Gem to the Application # 6) Resetting Gems back to the original version # 7) Breaking Gem List # # # 1) Which Gems are out of date? # # bundle outdated or use https://gemnasium.com/BCS-io/letting # # # 2) Update a Gem # # Update a single Gem using bundle update < gem name > # - example of pg: bundle update gp # # If a gem has not changed check what restrictions the Gemfile specifies # Taking pg as an example again. We can update to 0.18.1, 0.18.2, 0.18.3 # but not update to 0.19.1. To update to 0.19.1 you need to change the Gem # statement in this file and then run bundle update as above. # # gem 'pg', '~>0.18.0' => gem 'pg', '~>0.19.0' # # After updating a gem run rake though and if it passes before pushing up. # # # 3) Gemfile.lock # # You should never change Gemfile.lock directly. By changing Gemfile and # running bundle commands you change Gemfile.lock indirectly. # # # 4) Versioning # # Most Gems follow Semantic Versioning: http://semver.org/ # # Risk of causing a problem: # Low: 0.18.0 => 0.18.X - bug fixes # Low-Medium: 0.18.0 => 0.19.0 - New functionality but should not break old # functionality. # High: 0.18 = > 1.0.0 - Breaking changes with past code. # # # 5) Importance of a Gem to the Application # # Gems which are within development will not affect the production application: # # group :development do # gem 'better_errors', '~> 2.1.0' # end # # Gems without a block will affect the production application and you should be # more careful with the update. # # # 6) Resetting Gems back to the original version # # If you need to return your Gems to original version. # a) git checkout . # b) bundle install # # # GEMS THAT BREAK THE BUILD # # A list of Gems that if updated will break the application. # # Gem Using Last tested Gem Bug # rake 10.1.0 11.2.2 ? # # source 'https://rubygems.org' ruby '~> 2.5.0' # # Production # gem 'autoprefixer-rails', '~> 9.4.0' gem 'bcrypt', '~> 3.1.12' gem 'bootsnap', '>= 1.1.0', require: false gem 'coffee-rails', '~> 4.2.0' gem 'elasticsearch', '~> 6.0.0' gem 'elasticsearch-model', '~> 6.0.0' gem 'elasticsearch-rails', '~> 6.0.0' gem 'equalizer' gem 'font-awesome-rails' gem 'inline_svg', '~> 1.6.0' gem 'jbuilder', '~> 2.7.0' gem 'jquery-rails', '~> 4.3.0' # BREAKING GEM # 5.0.3 - causes CapybaraHelper to fail gem 'jquery-ui-rails', '6.0.1' # Kaminari before elasticsearch gem 'kaminari', '~> 1.1.0' gem 'lograge' gem 'nokogiri', '>= 1.8.2' # to avoid vulnerability gem 'pg', '~>0.20.0' # rails 5 required to use pg 1.0+ gem 'puma', '~> 4.3' gem 'rack-dev-mark', '~> 0.7.0' # corner banner on staging environment gem 'rails', '~> 5.2.4' gem 'rails-env-favicon' gem 'rake', '~> 12.3' gem 'redis', '~> 4.0' gem 'sass-rails', '~> 5.0.0' gem 'seedbank' gem 'sprockets', '~>3.7.0' gem 'turbolinks', '~> 5' gem 'uglifier', '~> 2.7.0' # # Development only # group :development do gem 'better_errors', '~> 2.5.0' gem 'binding_of_caller', '~> 0.8.0' gem 'brakeman', '~>4.3.0', require: false gem 'bullet', '~>5.9.0' gem 'listen', '>= 3.0.5', '< 3.2' gem 'rails-erd' gem 'rails_best_practices', '~>1.15.0' gem 'require_all', '~> 1.0' # 2.0 seems to break rails_best_practice # Remove to avoid vulnerability gem 'rubocop', '~> 0.74.0', require: false gem 'rubocop-performance', require: false gem 'rubocop-rails', require: false gem 'rubocop-rspec', require: false gem 'rubycritic', require: false gem 'scss_lint', '~> 0.57.0', require: false gem 'traceroute' # Access an IRB console on exception pages or by using <%= console %> in views gem 'web-console', '>= 3.3.0' end # # Development and testing # group :development, :test do # # BREAKING GEM # Throwing exceptions when it hits breakpoints # gem 'bundler-audit' gem 'byebug', platforms: %i[mri mingw x64_mingw] # 0.1.1 seems to introduce errors - Use this gem occasionally to weed out # performance errors with tests # gem 'capybara-slow_finder_errors', '0.1.0' gem 'meta_request' gem 'pry-rails', '~>0.3.0' gem 'pry-stack_explorer', '~>0.4.9.0' gem 'rack-mini-profiler', '~>1.0.0' gem 'rb-readline' gem 'spring' gem 'spring-commands-rspec' gem 'spring-watcher-listen', '~> 2.0.0' gem 'table_print' gem 'zonebie', '~> 0.6.0' end # # Testing # group :test do gem 'capybara', '~> 2.15.0' gem 'capybara-screenshot', '~> 1.0.0' # Create e.s. test node gem 'elasticsearch-extensions' gem 'rspec-rails', '~> 3.8.0' gem 'selenium-webdriver', '~>3.0' gem 'stackprof', '>= 0.2.9', require: false gem 'test-prof' gem 'timecop', '~>0.8.0' gem 'webdrivers', '~> 3.0' end
#!/usr/bin/env ruby require File.expand_path(File.dirname(__FILE__) + '/capfile.rb') require 'json' require 'optparse' options = {:path => ".", :output => "capfile.json"} OptionParser.new do |opts| opts.banner = "Usage: strano.rb [options]" opts.on('-p path', '--path=path', 'Application path') { |path| options[:path] = path } opts.on('-o output', '--output=output', 'Output file') { |output| options[:output] = output} end.parse! data = "{}" begin capfile = Capfile.new(options[:path]) data = {:tasks => capfile.tasks, :stages => capfile.stages } rescue Exception => e data = {:error => e.class.to_s, :message => e.message, :backtrace => e.backtrace.join("\n")} ensure File.open(options[:output],"w") { |file| file.write(data.to_json) } end
# frozen_string_literal: true ## # Follow the link to see how controllers are managed in Ruby on Rails: # {Action View Controller}[https://guides.rubyonrails.org/action_controller_overview.html]. class ApplicationController < ActionController::Base end
LanshanServer::Admin.controllers :cats do get :index do @title = "Cats" @cats = Cat.all.paginate(:page => params[:page]).order("created_at DESC") render 'cats/index' end get :new do @title = pat(:new_title, :model => 'cat') @cat = Cat.new render 'cats/new' end post :create do @cat = Cat.new(params[:cat]) if @cat.save @title = pat(:create_title, :model => "cat #{@cat.id}") flash[:success] = pat(:create_success, :model => 'Cat') params[:save_and_continue] ? redirect(url(:cats, :index)) : redirect(url(:cats, :edit, :id => @cat.id)) else @title = pat(:create_title, :model => 'cat') flash.now[:error] = pat(:create_error, :model => 'cat') render 'cats/new' end end get :edit, :with => :id do @title = pat(:edit_title, :model => "cat #{params[:id]}") @cat = Cat.find(params[:id]) if @cat render 'cats/edit' else flash[:warning] = pat(:create_error, :model => 'cat', :id => "#{params[:id]}") halt 404 end end put :update, :with => :id do @title = pat(:update_title, :model => "cat #{params[:id]}") @cat = Cat.find(params[:id]) if @cat if @cat.update_attributes(params[:cat]) flash[:success] = pat(:update_success, :model => 'Cat', :id => "#{params[:id]}") params[:save_and_continue] ? redirect(url(:cats, :index)) : redirect(url(:cats, :edit, :id => @cat.id)) else flash.now[:error] = pat(:update_error, :model => 'cat') render 'cats/edit' end else flash[:warning] = pat(:update_warning, :model => 'cat', :id => "#{params[:id]}") halt 404 end end delete :destroy, :with => :id do @title = "Cats" cat = Cat.find(params[:id]) if cat if cat.destroy flash[:success] = pat(:delete_success, :model => 'Cat', :id => "#{params[:id]}") else flash[:error] = pat(:delete_error, :model => 'cat') end redirect url(:cats, :index) else flash[:warning] = pat(:delete_warning, :model => 'cat', :id => "#{params[:id]}") halt 404 end end delete :destroy_many do @title = "Cats" unless params[:cat_ids] flash[:error] = pat(:destroy_many_error, :model => 'cat') redirect(url(:cats, :index)) end ids = params[:cat_ids].split(',').map(&:strip) cats = Cat.find(ids) if Cat.destroy cats flash[:success] = pat(:destroy_many_success, :model => 'Cats', :ids => "#{ids.to_sentence}") end redirect url(:cats, :index) end end
class CreateQuestions < ActiveRecord::Migration # No need to specify an 'id' column. # ActiveRecord auto create an integer field called 'id' with autoincrement def change create_table :questions do |t| t.string :title t.text :body t.timestamps null: false end end end
class RenamePrivateToIsPrivateInFeedUser < ActiveRecord::Migration def up rename_column :feed_users, :private, :is_private change_column :feed_users, :is_private, :boolean, default: true, null: false end def down rename_column :feed_users, :is_private, :private change_column :feed_users, :private, :boolean end end
module InvoicePDF # Generators should be contained within the <tt>InvoicePDF::Generators</tt> module. module Generators # The default InvoicePDF generator. class Standard include InvoicePDF::Helpers # Constructor here for future use... maybe. def initialize( options = {} ); end # Called from <tt>InvoicePDF::Invoice.save</tt>. +invoice+ is the <tt>InvoicePDF::Invoice</tt> instance. def create_pdf( invoice, to_file = true, hide_quantity_column = false, hide_price_column = false ) money_maker_options = { :currency_symbol => invoice.currency, :delimiter => invoice.separator, :decimal_symbol => invoice.decimal, :after_text => invoice.currency_text } Prawn::Document.new( :dpi => 72, :page_size => 'A4', :page_layout => :portrait ) do |pdf| pdf.move_down 10 # Set the default type pdf.font 'Helvetica', :size => 9 # Draw the company name pdf.text invoice.company, :style => :bold, :size => 20 # Invoice information pdf.bounding_box [ pdf.bounds.right - 125, pdf.bounds.top - 2 ], :width => 220 do data = [ [ Prawn::Table::Cell::Text.new( pdf, [0,0], :content => "<b>Invoice num</b>", :inline_format => true), invoice.number.to_s ], [ Prawn::Table::Cell::Text.new( pdf, [0,0], :content => "<b>Invoice Date</b>", :inline_format => true), invoice.invoice_date.to_s ], [ Prawn::Table::Cell::Text.new( pdf, [0,0], :content => "<b>Due Date</b>", :inline_format => true), invoice.due_date.to_s ] ] data.insert( 1, [ Prawn::Table::Cell::Text.new( pdf, [0,0], :content => "<b>PO number</b>", :inline_format => true), invoice.po_number ] ) unless invoice.po_number.nil? pdf.table(data, :cell_style => { :borders => [] }) do |table| table.column_widths = { 0 => 70, 1 => 150 } end end # End bounding_box pdf.move_down 65 var_y = pdf.y # Bill to section pdf.bounding_box [ 0, var_y ], :width => ( pdf.bounds.right / 3 ) do pdf.text 'Bill To', :style => :bold pdf.text "#{invoice.bill_to}\n#{invoice.bill_to_address}" end # End bill to section # Company address section pdf.bounding_box [ ( pdf.bounds.right / 3 ), var_y ], :width => ( pdf.bounds.right / 3 ) do pdf.text 'Pay To', :style => :bold pdf.text "#{invoice.company}\n#{invoice.company_address}" end # End company address section pdf.move_down 40 # Create items array for storage of invoice items items = [] headers = [] headers.push('Description') headers.push('Qty') if !hide_quantity_column headers.push('Price') if !hide_price_column headers.push('Total') items << headers cell_options = {:inline_format => true, :align => :right, :background_color => 'ffffff', :colspan => headers.length-1} cell_options_sum_number = { :background_color => 'CFCFCF' } invoice.items.map { |item| columns = [] columns << item.description columns << item.quantity if !hide_quantity_column columns << money_maker(item.price, money_maker_options) if !hide_price_column columns << money_maker(item.total, money_maker_options) items << columns #items << [ item.description, item.quantity, money_maker(item.price, money_maker_options), money_maker(item.total, money_maker_options) ] } # Insert subtotal items << [ create_cell(pdf, "<b>Subtotal</b>", cell_options), create_cell( pdf, money_maker(invoice.subtotal, money_maker_options),cell_options_sum_number) ] # Insert discount items << [ create_cell(pdf, "<b>Discount (#{invoice.discount}%)</b>", cell_options), create_cell( pdf, money_maker(invoice.discount_amount, money_maker_options),cell_options_sum_number) ] if invoice.discount_amount > 0 # Insert tax amount items << [ create_cell(pdf, "<b>Tax (#{invoice.tax}%)</b>", cell_options), create_cell( pdf, money_maker(invoice.tax_amount, money_maker_options),cell_options_sum_number) ] if invoice.tax_amount > 0 # Insert total items << [ create_cell(pdf, "<b>Total</b>", cell_options), create_cell( pdf, money_maker(invoice.total, money_maker_options),cell_options_sum_number) ] # Insert amount paid items << [ create_cell(pdf, "<b>Amount Paid</b>", cell_options), create_cell( pdf, money_maker(invoice.paid, money_maker_options),cell_options_sum_number) ] if invoice.paid > 0 # Insert total due items << [ create_cell(pdf, "<b>Amount Due</b>", cell_options), create_cell( pdf, money_maker(invoice.total_due, money_maker_options),cell_options_sum_number) ] # Create items table pdf.table(items, :header => true, :width => pdf.bounds.right, :row_colors => [ 'ffffff', 'f0f0f0' ], :cell_style => { :borders => [:left, :right, :top, :bottom], :border_color => '0000ff', :border_width => 0 }) do |table| table.column_widths = { 1 => 50, 2 => 75, 3 => 75 } table.rows(0).background_color = 'CFCFCF' # Header color end unless invoice.notes.nil? pdf.move_down 50 pdf.text 'Notes', :size => 10, :style => :bold pdf.text invoice.notes, :size => 8 end pdf.render_file "#{invoice.file_path}/#{invoice.file_name}" if to_file end end private def create_cell( pdf, content, options = {}) options.merge!({:content => content}) Prawn::Table::Cell::Text.new( pdf, [0,0], options ) end end end end
class Admin::ProductsController < Admin::BaseController # before_action :set_record, :only => [:show, :edit, :update, :destroy] def index @products_grid = initialize_grid(Admin::Product.all, per_page: 15) end def new @product = Admin::Product.new end def create @product = Admin::Product.create(product_params) if @product.save flash[:notice] = '新增成功' redirect_to :action => 'index' else render :new end end def edit end def update if @product.update_attributes(product_params) # 圖片在存檔時沒有更新seq欄位, 在找到解決方案前, 先手動方式處理 if !params[:admin_product][:main_pictures_attributes].nil? params[:admin_product][:main_pictures_attributes].each do |k, v| Admin::ProductMainPicture.find(v[:id]).update_attribute(:seq, v[:seq]) unless !Admin::ProductMainPicture.exists?(:id => v[:id]) end end # 圖片在存檔時沒有更新seq欄位, 在找到解決方案前, 先手動方式處理 if !params[:admin_product][:profile_pictures_attributes].nil? params[:admin_product][:profile_pictures_attributes].each do |k, v| Admin::ProductProfilePicture.find(v[:id]).update_attribute(:seq, v[:seq]) unless !Admin::ProductProfilePicture.exists?(:id => v[:id]) end end flash[:notice] = '修改成功' redirect_to :action => 'index' else render :edit end end def destroy @product.destroy flash[:notice] = '刪除成功' redirect_to :action => 'index' end private def set_record @product = Admin::Product.find(params[:id]) end def product_params params.require(:admin_product).permit(:id, :caption, :description, :unit_price, :sale_price, :caption_s, :description_s, :unit_price_s, :sale_price_s, :caption_e, :description_e, :unit_price_e, :sale_price_e, :cost, :itemcode, {sub_products_attributes: [:id, :size, :size_e,:size_s, :color,:color_s,:color_e, :qty, :itemcode, :seq, :_destroy]}, {main_pictures_attributes: [:id, :image_cache, :image, :seq, :_destroy]}, {profile_pictures_attributes: [:id, :image_cache, :image, :seq, :_destroy]}, category_ids:[] ) end end
module SportsDataApi module Nfl class Player def initialize(xml) if xml.is_a? Nokogiri::XML::Element player_ivar = self.instance_variable_set("@#{xml.name}", {}) self.class.class_eval { attr_reader :"#{xml.name}" } xml.attributes.each do | attr_name, attr_value| player_ivar[attr_name.to_sym] = attr_value.value end end end end end end
# frozen_string_literal: true require "English" require "faraday" module HubStep module Faraday # Faraday middleware for wrapping a request in a span. # # tracer = HubStep::Tracer.new # Faraday.new do |b| # b.request(:hubstep, tracer) # b.adapter(:typhoeus) # end class Middleware < ::Faraday::Middleware def initialize(app, tracer) super(app) @tracer = tracer end def call(request_env) # We pass `finish: false` so that the span won't have its end time # recorded until #on_complete runs (which could be after #call returns # if the request is asynchronous). @tracer.span("faraday", finish: false) do |span| begin span.configure { record_request(span, request_env) } @app.call(request_env).on_complete do |response_env| span.configure do record_response(span, response_env) span.finish if span.end_micros.nil? end end ensure span.configure { record_exception(span, $ERROR_INFO) } end end end private def record_request(span, request_env) method = request_env[:method].to_s.upcase span.operation_name = "Faraday #{method}" span.set_tag("component", "faraday") span.set_tag("http.url", request_env[:url]) span.set_tag("http.method", method) end def record_response(span, response_env) span.set_tag("http.status_code", response_env[:status]) end def record_exception(span, exception) return unless exception # The on_complete block may not be called if an exception is # thrown while processing the request, so we need to finish the # span here. @tracer.record_exception(span, exception) span.finish if span.end_micros.nil? end end end end Faraday::Request.register_middleware hubstep: HubStep::Faraday::Middleware
require 'spec_helper' describe TitlesController do describe 'routing' do it 'routes to #index' do expect(get: '/titles').to route_to('titles#index') expect(get: '/titles/all').to route_to('titles#index', initial: 'all') expect(get: '/titles/a').to route_to('titles#index', initial: 'a') end end end
class ReviewsController < ApplicationController before_action :find_book before_action :find_review, only: [:edit, :update, :destroy, :show] before_action :authenticate_user!, only: [:new, :edit] def index @reviews = @book.reviews respond_to do |format| format.json {render json: @reviews} format.html {render 'index.html', layout: false} end end def new @review = Review.new end def show render json: @review end def create @review = @book.reviews.build(review_params) @review.book_id = @book.id @review.user_id = current_user.id if @review.save respond_to do |f| f.html {redirect_to book_path(@book)} f.json {render json: @review, status: 201} end else render 'books/show' end end def edit end def update if @review.update(review_params) redirect_to book_path(@book) else render :edit end end def destroy @review.destroy redirect_to book_path(@book) end private def review_params params.require(:review).permit(:rating, :comment) end def find_book @book = Book.find(params[:book_id]) end def find_review @review = Review.find(params[:id]) end end
#!/usr/bin/ruby -w def prompt(*args) input_arg=false until input_arg do print(*args) value=String(gets) rescue false input_arg=value rescue false if value =~ /[A-D]/ # prompt again if the argument isn't A, B, C, or D input_arg=true else input_arg=false end end return value end class Question CHOICE_INDICATORS = ["A", "B", "C", "D"] attr_reader :meta, :is_correct attr_accessor :text, :choices, :correct_answer, :user_answer def initialize(text = '', choices = '', correct_answer = '', user_answer = '') @text = text # text of the question @choices = choices # the multiple choice selection @correct_answer = correct_answer # the correct answer to the multiple choice selection @user_answer = '' # this is initialized as nothing, because is set after initialization occurs @meta = CHOICE_INDICATORS # some meta data used @is_correct = false # flag for checking if the question was answered wrong or not end # prints the question and the multiple choice selection def printText puts @text @choices.each do |choice| puts "#{choice.indicator}. #{choice.text}\n" end puts "\n" end # this is how the program sets the answer; it checks against the choices stored in this class and sets to the appropriate one def setUserAnswer(chosen_indicator) @choices.each do |choice| if chosen_indicator.match(choice.indicator) @user_answer = choice end end end # checks the answer to see if it's correct, and triggers the flag; also appends choices with after-analysis indicators def checkUserAnswer if @user_answer == @correct_answer @is_correct = true else @user_answer.indicator = "x " + @user_answer.indicator end @correct_answer.indicator = "> " + @correct_answer.indicator end end class Choice attr_accessor :indicator, :text def initialize(indicator, text) @indicator = indicator @text = text end end def selectionHash selection_hash = Hash.new selection_hash["vowel"] = "あいうえお" selection_hash["K"] = "かきくけこ" selection_hash["S"] = "さしすせそ" selection_hash["T"] = "たちつてと" selection_hash["N"] = "なにぬねの" selection_hash["H"] = "はひふへほ" selection_hash["M"] = "まみむめも" selection_hash["Y"] = "やゆよ" selection_hash["R"] = "らりるれろ" selection_hash["W"] = "わを" return selection_hash end def emoji_score(score) emoji = case score when 10 then ":D" when 8..9 then ":)" when 3..7 then ":/" when 1..5 then ":(" else "Hmmmm..." end return emoji end def randomizeChoices(choices_hash, question_keys, answer_key) letters = Question.new.meta # gets the multiple choice letters (could potentially be modified if you wanted more choices) question_keys.delete(answer_key) # remove the question key from array # get random keys excluding the current one which is the answer key rand_question_keys = question_keys.sample(letters.length - 1) rand_question_keys.push(answer_key) # put the answer key with the random keys rand_question_keys = rand_question_keys.sample(letters.length) # randomize again with the answer key inserted # creates the choice objects sequentially with the choice text obtained from the hash map choices = [] letters.each_with_index do |letter, i| choices << Choice.new(letter, choices_hash[rand_question_keys[i]]) end question_keys.unshift(answer_key) # put question key back to beginning of array return choices end def quiz(question_text_template) question_keys = ["vowel", "K", "S", "T", "N", "H", "M", "Y", "R", "W"] questions = [] choices_hash = selectionHash # grabs the hash map used for randomizeChoices question_keys.each do |key| choices = randomizeChoices(choices_hash, question_keys, key) correct_answer = choices.select{ |choice| choice.text.match(choices_hash[key]) } # grabs the correct answer and makes sure it's in the form of a choice object # sets the question with the text, complete list of randomized choices, and the correct choice question = Question.new("#{question_text_template} #{key} syllables?\n", choices, correct_answer[0]) question.printText # prints the context for the prompt # you can set chosen_indicator to a letter of your choice to test (instead of being prompted 10 times) chosen_indicator = prompt "What's your choice? " puts "\n" question.setUserAnswer(chosen_indicator) question.checkUserAnswer questions << question end # filters through question list to check for the wrong answers indicated by the correct flag wrong_questions = questions.select{ |question| !question.is_correct } # gets the score from subtracting the array of the wrong answers from the initial questions array score = questions.length - wrong_questions.length # calculates an emoji, because why not (perks of administering a quiz) emoji = emoji_score(score) puts "\nYou scored a #{score} out of 10 #{emoji}\n\n\n" # first condition to display wrong questions and the appropriate answers if score < 10 puts "These are the questions you got wrong: \n\n" wrong_questions.each do |question| question.printText end end # second condition to recurse through quiz again if the score is bad enough if score <= 5 puts "\nYou got less than half right! You must retake the quiz!\n\n\n\n" # i know this isn't how you wanted it (more so a list of longer questions), but this is the best way # to represent a multiple choice quiz quiz("Which one of these is the correct row for hirigana") # slightly reword the questions end end quiz("What's the correct row that contains the hirigana")
require 'spec_helper' # I can't get this to work T_T feature 'User registers' do background do visit root_path click_link 'Sign up' end scenario 'successfully' do fill_in 'Email', with: 'joe@example.com' fill_in 'Password', with: 'password' fill_in 'Password confirmation', with: 'password' click_button 'Sign up' expect(page).to have_content 'Welcome! You have signed up successfully.' end scenario 'unsuccessfully due to required fields missing' do click_button 'Sign up' expect(page).to have_content "Email can't be blank" expect(page).to have_content "Password can't be blank" end end
# frozen_string_literal: true module X25519 # Known-good inputs and outputs for X25519 functions module TestVectors # Test vector for variable-base scalar multiplication VariableBaseVector = Struct.new(:scalar, :input_coord, :output_coord) # X25519 variable-base test vectors from RFC 7748 VARIABLE_BASE = [ VariableBaseVector.new( "a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4", "e6db6867583030db3594c1a424b15f7c726624ec26b3353b10a903a6d0ab1c4c", "c3da55379de9c6908e94ea4df28d084f32eccf03491c71f754b4075577a28552" ), VariableBaseVector.new( "4b66e9d4d1b4673c5ad22691957d6af5c11b6421e0ea01d42ca4169e7918ba0d", "e5210f12786811d3f4b7959d0538ae2c31dbe7106fc03c3efc4cd549c715a493", "95cbde9476e8907d7aade45cb4b873f88b595a68799fa152e6f8f7647aac7957" ) ].freeze # Test vector for fixed-base scalar multiplication FixedBaseVector = Struct.new(:scalar, :output_coord) # X25519 fixed-base test vectors, generated via RbNaCl/libsodium FIXED_BASE = [ FixedBaseVector.new( "a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4", "1c9fd88f45606d932a80c71824ae151d15d73e77de38e8e000852e614fae7019" ), FixedBaseVector.new( "4b66e9d4d1b4673c5ad22691957d6af5c11b6421e0ea01d42ca4169e7918ba0d", "ff63fe57bfbf43fa3f563628b149af704d3db625369c49983650347a6a71e00e" ) ].freeze end end
require 'rails_helper' RSpec.describe ProductType, :type => :model do let(:product_type) {FactoryGirl.create(:product_type)} context "Factory settings for product_type" do it "should validate the product_type factories" do expect(FactoryGirl.create(:product_type).valid?).to be true end end describe ProductType do it { should validate_presence_of :product_type_name } it { should allow_value('Shirt').for(:product_type_name )} end end
class EmailAuthentications::PasswordsController < Devise::PasswordsController def edit users_email_authentication = resource_class.with_reset_password_token(params["reset_password_token"]) return render "expired_reset_token" unless users_email_authentication&.reset_password_period_valid? super end end
# The fake Resque class. This needs to be loaded after the real Resque # for the assertions in +ResqueUnit::Assertions+ to work. module Resque # Resets all the queues to the empty state. This should be called in # your test's +setup+ method until I can figure out a way for it to # automatically be called. def self.reset! @queue = Hash.new { |h, k| h[k] = [] } end # Returns an array of all the jobs that have been queued. Each # element is of the form +{:klass => klass, :args => args}+ where # +klass+ is the job's class and +args+ is an array of the arguments # passed to the job. def self.queue(queue) self.reset! unless @queue @queue[queue] end # Executes all jobs in all queues in an undefined order. def self.run! old_queue = @queue.dup reset! old_queue.each do |k, v| while job = v.shift job[:klass].perform(*job[:args]) end end end # Returns the size of the given queue def self.size(queue) self.reset! unless @queue @queue[queue].length end # :nodoc: def self.enqueue(klass, *args) queue(queue_for(klass)) << {:klass => klass, :args => args} end # :nodoc: def self.queue_for(klass) klass.instance_variable_get(:@queue) || (klass.respond_to?(:queue) && klass.queue) end end
class Work < ActiveRecord::Base belongs_to :composer has_and_belongs_to_many :editions, :order => "year ASC" has_and_belongs_to_many :instruments PERIODS = { [1650..1750, %w{ EN DE FR IT ES NL }] => "Baroque", [1751..1810, %w{ EN IT DE NL }] => "Classical", [1751..1830, %w{ FR }] => "Classical", [1837..1901, %w{ EN }] => "Victorian", [1820..1897, %w{ DE FR }] => "Romantic" } #Calculating a work’s period def period pkey = PERIODS.keys.find do |yrange, countries| yrange.include?(year) && countries.include?(country) end PERIODS[pkey] || century end #Teaching a work what its century is def century c = (year - 1).to_s[0, 2].succ c += case c when "21" then "st" else "th" end c + "century" end # Which publishers have published editions of this work? def publishers editions.map {|e| e.publisher}.uniq end # What country is this work from? def country composer.country end # Which customers have ordered this work? def ordered_by editions.map {|e| e.orders}.flatten.map {|o| o.customer}.uniq end # What key is this work in? def key kee end #Formatting the names of the work’s instruments def nice_instruments instrs = instruments.map {|inst| inst.name} ordered = %w{flute oboe violin viola cello piano orchestra} instrs = instrs.sort_by {|i| ordered.index(i) || 0} case instrs.size when 0 nil when 1 instrs[0] when 2 instrs.join(" and ") else instrs[0..-2].join(", ") + ", and " + instrs[-1] end end #Formatting a work’s opus number def nice_opus if /^\d/.match(opus) "op. #{opus}" else opus end end #The work’s prettified title def nice_title t, k, o, i = title, key, nice_opus, nice_instruments "#{t} #{"in #{k}" if k} #{", #{o}" if o} #{", for #{i} if i"}" end #Determining all periods represented in the stock def self.all_periods find(:all).map {|c| c.period}.flatten.uniq.sort end #Determining sales rankings for works def self.sales_rankings r = Hash.new(0) find(:all).each do |work| work.editions.each do |ed| r[work.id] += ed.orders.size end end r end end
class Api::V1::EvaluationsController < ApplicationController before_action :authorized, only: [:create, :update] def create evaluation = Evaluation.new(eval_params) if evaluation.save render json: evaluation else render json: {errors: evaluation.errors.full_messages} end end def update evaluation = Evaluation.find(params[:id]) evaluation.assign_attributes(eval_params) if evaluation.save render json: evaluation else render json: {errors: evaluation.errors.full_messages} end end private def eval_params params.permit(:plant_id, :number_fruit, :height, :overall_health, :notes) end end
FactoryBot.define do factory :order_address do postal_code { '123-4567' } prefecture_id { 1 } city { '町田市' } addresses { '8-9' } building { 'tesuto' } phone_number { '09099999999' } token { 'tok_4f612c8e1089f52009d0980d151c' } end end
require 'spec_helper' describe Study do let(:nicknames) {%w(nickname1 nickname2)} let(:study_name) {"study_1"} it "should create new study with nicknames" do study = Study.new(official_name: study_name, nicknames: nicknames) study.study_nicknames.length.should == nicknames.length study.official_name.should == study_name study.study_nicknames.each {|sn| nicknames.should include sn.nickname} study.save StudyNickname.current.count.should == 2 StudyNickname.current.each {|sn| sn.study.should == study} end it "should not orphan study nickname objects" do study = Study.new(official_name: study_name, nicknames: nicknames) study.save study.reload study.nicknames = [] study.study_nicknames.should be_empty study.save study.study_nicknames.should be_empty StudyNickname.current.count.should == 0 end it "should allow study nicknames to be added in semicolon-delimited string" do nickname_string = nicknames.join("; ") study = Study.create(official_name: study_name, nicknames: nickname_string) study.study_nicknames.each {|sn| nicknames.should include sn.nickname} end end
require 'rails_helper' RSpec.describe User, type: :model do it { should have_many(:questions) } it { should have_many(:exam_results).class_name('ExamResult') } # it { should have_many(:categories).through(:categorizations) } it 'should filter by role' do student = create(:student) teacher = create(:teacher) expect(User.all_students).to include(student) expect(User.all_teachers).to include(teacher) end it 'should validate presence of required fields' do record = User.new record.fullname = '' # invalid state record.valid? # run validations expect(record.errors[:fullname]).to include("can't be blank") # check for presence of error record.username = '' # invalid state record.valid? # run validations expect(record.errors[:username]).to include("can't be blank") # check for presence of error record.email = '' # invalid state record.valid? # run validations expect(record.errors[:email]).to include("can't be blank") # check for presence of error record.email = 'valid@email.com' # valid state record.valid? # run validations expect(record.errors[:email]).not_to include("can't be blank") # check for absence of error record.role = '' # invalid state record.valid? # run validations expect(record.errors[:role]).to include("can't be blank") # check for presence of error end it 'should valid uniqueness' do student = create(:student) user = User.new user.fullname = student.fullname user.valid? expect(user.errors[:fullname]).to include('must be unique!') user.username = student.username user.valid? expect(user.errors[:username]).to include('must be unique!') user.email = student.email user.valid? expect(user.errors[:email]).to include('must be unique!') end it 'should validate invalid email format' do user = User.new user.email = 'invalid-email' user.valid? expect(user.errors[:email]).to include('is invalid') end it 'should check user role' do admin = create(:admin) student = create(:student) teacher = create(:teacher) expect(admin.is_admin?).to eq(true) expect(student.is_student?).to eq(true) expect(teacher.is_teacher?).to eq(true) end end
class PullRequestsController < ApplicationController def index team = Team.find_by(slack_team_id: params[:team_id]) channel = Channel.find_by(slack_channel_id: params[:channel_id]) if team.nil? || channel.nil? render text: "Something went wrong, PRBot can't find your team or channel" else pull_requests = PullRequest.includes(:user).where(approved_at: nil, team: team, channel: channel).all render text: PullRequestListMessage.message(pull_requests) end end def create pull_request = PullRequestParser.parse(params) if pull_request.approved? pull_request.approved = false pull_request.save end if pull_request.nil? render text: 'PRBot could not find a pull request in this message. Please include the full github link.' else response_code = PullRequestMessenger.post(pull_request) if response_code == '200' render text: "Pull request received! #{COMPLIMENTS[rand(0..COMPLIMENTS.size - 1)].to_s}" elsif response_code.nil? render text: "Please add a web hook url so that prbot can post in #{pull_request.channel.name}", status: :bad_request else render text: "Pull request recorded. The web hook appears to be responding slowly." end end end end
# Copyright (c) 2006, 2007 Ruffdogs Software, Inc. # Authors: Adam Lebsack <adam@holonyx.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. module Restore module Restorer require 'restore/restorer' class Filesystem < Restore::Restorer::Base def initialize(target, snapshot, logger, args) super @subdir = args[:subdir] @file_ids = args[:file_ids] end def execute super create_directory(@subdir) unless @subdir.empty? @copied = {} @file_ids.each do |id| if file = target.files.find(id) restore_file(file) end end end protected def restore_file(file) return if @copied[file.path] if (log = file.log_for_snapshot(snapshot)) && log.event != 'D' && log.btime && !log.pruned logger.info "Restoring #{file.path}" begin copy_file(file, log) rescue => e logger.info e.to_s #logger.info e.backtrace.join("\n") end @copied[file.path] = true if log.file_type == 'D' file.children.each do |c| restore_file(c) end end end end def create_directory(path) end def copy_file(file, log) end end end end
class LocationsController < ApplicationController load_and_authorize_resource :except => [:locations_for_topic] # GET /locations # GET /locations.json def index @locations = Location.all @markers = Location.all.to_gmaps4rails respond_to do |format| format.html # index.html.erb format.json { render json: @locations } end end def locations_for_topic unless params[:topic_id].blank? query = Location.select("#{Location.table_name}.*, (SELECT COUNT(*) FROM locations_topics WHERE location_id = #{Location.table_name}.id) as total_topics, (SELECT COUNT(*) FROM locations_topics WHERE location_id = #{Location.table_name}.id AND topic_id = #{params[:topic_id].to_i}) as matched_topics") else query = Location.select("#{Location.table_name}.*, (SELECT COUNT(*) FROM locations_topics WHERE location_id = #{Location.table_name}.id) as total_topics, 0 as matched_topics") end @locations = query.to_a end end
# frozen_string_literal: true require 'test_helper' class DateRangeTest < ActiveSupport::TestCase def setup @start = Date.new(2021, 5, 10) @stop = Date.new(2021, 5, 12) @daterange = DateRange.new(@start, @stop) end test 'includes_date? returns true for start date' do assert @daterange.includes_date?(@start) end test 'includes_date? returns true for stop date' do assert @daterange.includes_date?(@stop) end test 'includes_date? returns false for date out of range' do assert @daterange.includes_date?(@stop - 1) end test 'includes_date_range? is true for daterange within this daterange' do daterange2 = DateRange.new(@start + 1, @stop - 1) assert @daterange.includes_date_range?(daterange2) end test 'includes_date_range? is true for self' do assert @daterange.includes_date_range?(@daterange) end test 'overlaps_date_range? is true for overlapping daterange' do daterange2 = DateRange.new(@start - 1, @stop - 1) assert @daterange.overlaps_date_range?(daterange2) end test 'overlaps_date_range? is false for self' do assert @daterange.overlaps_date_range?(@daterange) end test 'returns a string representation of self' do assert_equal '10-May-2021 to 12-May-2021', @daterange.to_s end test 'verifies a valid date range' do assert @daterange.valid? end test 'a nil start is not valid' do daterange = DateRange.new(nil, @stop) refute daterange.valid? end test 'a nil stop is not valid' do daterange = DateRange.new(@start, nil) refute daterange.valid? end test 'a non Date start is not valid' do daterange = DateRange.new('a', @stop) refute daterange.valid? end test 'a non Date stop is not valid' do daterange = DateRange.new(@start, 'a') refute daterange.valid? end test 'start must be earlier than stop to be valid' do daterange = DateRange.new(@stop, @start) refute daterange.valid? end test 'start cannot = stop to be valid' do daterange = DateRange.new(@start, @start) refute daterange.valid? end end
class BooksController < ApplicationController before_action :param_id, only: [:edit,:show, :update, :destroy] def index @books = Book.all.order(title: :asc) end def show end def new @book = Book.new end def create @book = Book.new param_permit if @book.save redirect_to books_path end end def edit end def update if @book.update param_permit redirect_to books_path else redirect_to books_path, notice: "buruk" end end def destroy if @book.destroy redirect_to books_path, notice: "Buku Berhasil Di Hapus" end end private def param_id @book = Book.find(params[:id]) end def param_permit params.require(:book).permit(:title,:price,:page,:description) end end
Then(/^I should see the Edit page for the post$/) do expect(current_path).to eq edit_post_path(@post.id) end When(/^I fill the '(.+)' field with '(.+)'$/) do |field, text| fill_in field, with: text end When(/^I click the '(.+)' button$/) do |button| click_button button end Then(/^I should see the content '(.+)' on the page$/) do |content| expect(page).to have_content content end Then(/^I should see the Edit Comment Page$/) do expect(current_path).to eq edit_post_comment_path(@post.id, @comment.id) end
class Employee < ActiveRecord::Base belongs_to :office belongs_to :reportee, :class_name => "Employee" has_many :customers, :foreign_key => "sales_rep_employee_id" end
=begin In the previous exercise, we developed a procedural method for computing the value of the nth Fibonacci numbers. This method was really fast, computing the 20899 digit 100,001st Fibonacci sequence almost instantly. In this exercise, you are going to compute a method that returns the last digit of the nth Fibonacci number. Examples: =end def fibonacci_last(nth) fibonacci(nth).to_s[-1].to_i end def fibonacci_last(nth) last_2 = [1, 1] 3.upto(nth) do last_2 = [last_2.last, (last_2.first + last_2.last) % 10] end last_2.last end puts fibonacci_last(15) # -> 0 (the 15th Fibonacci number is 610) puts fibonacci_last(20) # -> 5 (the 20th Fibonacci number is 6765) puts fibonacci_last(100) # -> 5 (the 100th Fibonacci number is 354224848179261915075) puts fibonacci_last(100_001) # -> 1 (this is a 20899 digit number) puts fibonacci_last(1_000_007) # -> 3 (this is a 208989 digit number) puts fibonacci_last(123456789) # -> 4
require_relative 'participant' class Auditor attr_reader :name, :id def initialize(p_name, p_id) @name = p_name @id = p_id end # Push model # Will probably stick to Push model as it sends only required information to observer. # In the context this code, there is only 1 auditor who's auditing all the players and as per # the implementation just requires 2 fields from participant class. # Passing entire instance of Participant would give too much knowledge to Observer which is not needed here. def update(name, num_attempts) if num_attempts <= 5 #puts "#{name} is not genuine." else puts "#{name} is genuine: No of attempts required: #{num_attempts}." end end # Pull Model def update(player) # In the background get methods of num_attempts and name are being called. if player.num_attempts <= 5 #puts "#{name} is not genuine." else puts "#{player.name} is genuine: No of attempts required: #{player.num_attempts}." end end end
class Client < ActiveRecord::Base has_many :transactions enum status: [:delay, :at_day, :service_suspend, :banned] end
require 'open-uri' require 'date' require "tmpdir" require "digest" module ManticoreHelper def self.fetch_version_and_url(formula_name, base_url, pattern) highest_version, highest_version_url = self.find_version_and_url(formula_name, base_url, pattern) filepath, sha256 = download_file(formula_name, highest_version_url) { version: highest_version, file_url: "file://#{filepath}", sha256: sha256 } end def self.find_version_and_url(formula_name, base_url, pattern) content = URI.open(base_url).read versions = [] content.scan(pattern) do |match| semver = match[1] separator = match[2] date = match[3] hash_id = match[4] versions << { semver: Gem::Version.new(semver), separator: separator, date: date, hash_id: hash_id, file: "#{match[0]}#{semver}#{separator}#{date}#{hash_id}#{match[5]}" } end if versions.empty? raise "Could not find versions by using provided URL and pattern" end versions.sort_by! { |v| [v[:semver], v[:date]] }.reverse! highest_version = "#{versions.first[:semver]}#{versions.first[:separator]}#{versions.first[:date]}#{versions.first[:hash_id]}" highest_version_url = base_url + versions.first[:file] if highest_version.nil? || highest_version_url.nil? raise "Could not find version or URL for '#{formula_name}' with the given pattern: #{pattern}" end [highest_version, highest_version_url] end def self.fetch_version_from_url(url) version = url.match(/(?<=-)[\d\w\._]+(?=-|\_)/).to_s formula_name = url.match(/(?<=release\/)[\w-]+(?=-)/).to_s filepath, sha256 = download_file(formula_name, url) { version: version, file_url: "file://#{filepath}", sha256: sha256 } end def self.download_file(formula_name, url) tmpdir = Dir.mktmpdir filepath = "#{tmpdir}/#{formula_name}.tar.gz" File.open(filepath, "wb") do |saved_file| open(url, "rb") do |remote_file| saved_file.write(remote_file.read) end end [filepath, Digest::SHA256.file(filepath).hexdigest] end end
YELLOW='' RESET='' ignore %r!^out/!, %r!^testdata/gen/.*/HAVE!, %r!^tmp/! def run(cmdline) puts "#{YELLOW}+#{cmdline}#{RESET}" system cmdline end def run_tests(file, flags='') parent = File.dirname file sources = Dir["#{parent}/*.go"].reject{|p| p.end_with? '_test.go' }.uniq.join ' ' sources = "common_test.go #{sources}" if file != 'common_test.go' # Assume that https://github.com/rhysd/gotest is installed run "gotest #{flags} #{file} #{sources}" end guard :shell do watch /\.go$/ do |m| puts "#{Time.now}: #{m[0]}" case m[0] when /_test\.go$/ run_tests m[0] when %r{^testdata/gen/} run_tests 'generate_test.go' when %r{^testdata/trans/ok/([^/]+)/} run_tests 'translate_test.go', "-run TestTranslationOK/#{$1}" when %r{^testdata/trans/error/([^/]+)/} run_tests 'translate_test.go', "-run TestTranslationError/#{$1}" when %r{^[^/]+\.go$} run 'go build ./cmd/trygo' run "golint #{m[0]}" run 'go vet' end end watch /\.txt$/ do |m| puts "#{Time.now}: #{m[0]}" case m[0] when %r{^testdata/trans/error/([^/]+)/message\.txt$} run_tests 'translate_test.go', "-run TestTranslationError/#{$1}" end end end
class RenameGigDatesColumnName < ActiveRecord::Migration[5.0] def change rename_column :gigs, :start, :start_date rename_column :gigs, :end, :end_date end end
require 'uri' require 'net/https' module Castronaut module Models class ServiceTicket < ActiveRecord::Base include Castronaut::Models::Consumeable include Castronaut::Models::Dispenser MissingMessage = "Ticket or service parameter was missing in the request." belongs_to :ticket_granting_ticket has_many :proxy_granting_tickets, :dependent => :destroy before_validation :dispense_ticket, :if => :new_record? validates_presence_of :ticket, :client_hostname, :service, :username, :ticket_granting_ticket def self.generate_ticket_for(service, client_host, ticket_granting_ticket) create! :service => service, :username => ticket_granting_ticket.username, :client_hostname => client_host, :ticket_granting_ticket => ticket_granting_ticket end def self.validate_ticket(service, ticket, allow_proxy_tickets = false) return Castronaut::TicketResult.new(nil, MissingMessage, "INVALID_REQUEST") unless service && ticket service_ticket = find_by_ticket(ticket) return Castronaut::TicketResult.new(nil, "Ticket #{ticket} not recognized.", "INVALID_TICKET") unless service_ticket return Castronaut::TicketResult.new(service_ticket, "Ticket '#{ticket}' has already been used up.", "INVALID_TICKET") if service_ticket.consumed? service_ticket.consume! if service_ticket === Castronaut::Models::ProxyTicket && !allow_proxy_tickets return Castronaut::TicketResult.new(service_ticket, "Ticket '#{ticket}' is a proxy ticket, but only service tickets are allowed here.", "INVALID_TICKET") end return Castronaut::TicketResult.new(service_ticket, "Ticket '#{ticket}' has expired.", "INVALID_TICKET") if service_ticket.expired? mismatched_service_message = "The ticket '#{ticket}' belonging to user '#{service_ticket.username}' is valid, but the requested service '#{service}' does not match the service '#{service_ticket.service}' associated with this ticket." return Castronaut::TicketResult.new(service_ticket, mismatched_service_message, "INVALID_SERVICE") unless service_ticket.matches_service?(service) Castronaut::TicketResult.new(service_ticket, nil, "success") end def matches_service?(other_service) service == other_service end def service_uri return nil if service.blank? begin raw_uri = URI.parse(service) if service.include? "?" if raw_uri.query.empty? query_separator = "" else query_separator = "&" end else query_separator = "?" end "#{service}#{query_separator}ticket=#{ticket}" rescue URI::InvalidURIError nil end end def ticket_prefix "ST" end def expired? # Time.now - service_ticket.created_on > CASServer::Conf.service_ticket_expiry end def proxies end end end end
class ConcreteHolidays::ChristmasObserved include ConcreteHolidays::Calculations def self.date(year) # December 25th to_weekday_if_weekend(Date.new(year,12,25)) end end
require 'minitest/autorun' require 'minitest/capistrano' require 'capistrano/fanfare' require 'capistrano/fanfare/assets' # # Rake mixes in FileUtils methods into Capistrano::Configuration::Namespace as # private methods which will cause a method/task namespace collision when the # `deploy:assets:symlink' task is created. # # So, if we are in a Rake context, nuke :symlink in the Namespace class--we # won't be using it directly in this codebase but this feels so very, very # wrong (here be dragons). # if defined?(Rake::DSL) Capistrano::Configuration::Namespaces::Namespace.class_eval { undef :symlink } end describe Capistrano::Fanfare::Assets do before do @config = Capistrano::Configuration.new Capistrano::Fanfare::Assets.load_into(@config) @config.extend(MiniTest::Capistrano::ConfigurationExtension) # @orig_config = Capistrano::Configuration.instance # Capistrano::Configuration.instance = @config end after do # Capistrano::Configuration.instance = @orig_config end describe "for namespace :deploy" do it "creates a deploy:assets:symlink task" do @config.must_have_task "deploy:assets:symlink" end it "creates a deploy:assets:precompile task" do @config.must_have_task "deploy:assets:precompile" end it "creates a deploy:assets:clean task" do @config.must_have_task "deploy:assets:clean" end end end
module Spree # file uploaded for template class TemplateFile < ActiveRecord::Base belongs_to :template_theme, :foreign_key=>"theme_id" #validates_uniqueness_of :file_name has_attached_file :attachment self.attachment_definitions[:attachment][:url] = "/shops/:rails_env/1/:class/:id/:basename_:style.:extension" self.attachment_definitions[:attachment][:path] = ":rails_root/public/shops/:rails_env/1/:class/:id/:basename_:style.:extension" self.attachment_definitions[:attachment][:default_url] = "/images/:style/missing.png" delegate :url, :to => :attachment #it is required while import theme with new template_file. we would set theme.assigned_resources while import. attr_accessor :page_layout_id attr_accessible :theme_id, :attachment, :page_layout_id #for resource_class.resourceful scope :resourceful, ->(theme){ where(:theme_id=>theme.id)} end end
def require_if task, name require name if ARGV[0] =~ %r{^#{task}} end require 'rake' require 'rake/testtask' require 'rake/rdoctask' require 'spec/rake/spectask' require 'spec/rake/verify_rcov' require_if :metrics, 'metric_fu' task :default => :spec # run with rake spec Spec::Rake::SpecTask.new(:spec) do |t| t.spec_opts = %w{--colour --format progress --loadby mtime --reverse} t.spec_files = Dir.glob('spec/**/*_spec.rb') t.warning = false end # run with rake rcov Spec::Rake::SpecTask.new(:rcov) do |t| t.spec_opts = %w{--colour --format progress --loadby mtime --reverse} t.spec_files = Dir.glob('spec/**/*_spec.rb') t.warning = false t.rcov = true puts "Open coverage/index.html for the rcov results." end begin require 'jeweler' Jeweler::Tasks.new do |gemspec| gemspec.name = "view_models" gemspec.summary = "A model proxy for Rails views. Helps you keep the representation of a model and the model itself separate." gemspec.email = "florian.hanke@gmail.com" gemspec.homepage = "http://floere.github.com/view_models" gemspec.description = "The view models gem adds the missing R (Representation) to Rails' MVC. It provides simple proxy functionality for your models and thus helps you keep the model and view representations of a model separate, as it should be. Also, you can define helper methods on the (view) model instead of globally to keep them focused, more quickly understood and more easily testable. View Models also introduce hierarchical rendering for your hierarchical models. If the account view is not defined for the subclass FemaleUser, it checks if it is defined for User, for example, to see when there is no specific view, if there is a general view. So, in other words: Polymorphism not just in the model, but also in the view. Have fun!" gemspec.authors = ["Florian Hanke", "Kaspar Schiess", "Niko Dittmann", "Andreas Schacke"] gemspec.rdoc_options = ["--inline-source", "--charset=UTF-8"] gemspec.files = FileList["[A-Z]*", "{generators,lib,rails,spec}/**/*"] gemspec.add_dependency 'rails', '>= 2.2.0' gemspec.add_development_dependency 'rspec', '>=1.2.9' end Jeweler::GemcutterTasks.new rescue LoadError => e puts "Jeweler not available (#{e}). Install it with: sudo gem install technicalpickles-jeweler -s http://gems.github.com" end
class ChangeResourceTitleType < ActiveRecord::Migration def change change_column :resources, :title, :text end end
class Api::TweetSentimentsController < Api::ApiController before_filter :admin_access def index render json: TweetSentiment.all end def create key = Tracker.where(:keyword => params[:keyword]).first list = TweetSentiment.new(:tracker_id => key.id, :date => params[:date], :sentiment => params[:sentiment]) if !list.save render status: 422, json: { message: "Failed to create Tweet Sentiment", tweet: list }.to_json and return end render status: 200, json: { message: "Successfully created Tweet Sentiment" }.to_json end def delete key = Tracker.where(:keyword => params[:keyword]).first if TweetSentiment.exists?(:tracker_id => key.id, :date => params[:date]) list = TweetSentiment.where(:tracker_id => key.id, :date => params[:date]) list.destroy_all render status: 200, json: { message: "Successfully delted Tweet Sentiment" }.to_json else render status: 422, json: { message: "Failed to delete Tweet Sentiment" }.to_json end end private def json_params params.require(:tweet_sentiment).permit(:keyword, :date, :sentiment) end def admin_access head :unauthorized unless Rails.application.secrets.api_key == params[:api_key] end end
require 'spec_helper' describe Order, :model => :order do let!(:status) { Fabricate(:status) } let(:order) { Fabricate(:order) } let(:cancelled) { StoreEngine::Status::CANCELLED } let(:shipped) { StoreEngine::Status::SHIPPED } let(:returned) { StoreEngine::Status::RETURNED } let(:paid) { StoreEngine::Status::PAID } context "#update_status" do it "changes pending status to cancelled" do order.should_receive(:status).and_return(status) cancelled_status = Fabricate(:status, :name => cancelled) Status.stub(:find_by_name).with(cancelled).and_return(cancelled_status) order.should_receive(:update_attributes).with(:status => cancelled_status) order.update_status end it "changes shipped to returned" do shipped_status = Fabricate(:status, :name => shipped) order.should_receive(:status).and_return(shipped_status) returned_status = Fabricate(:status, :name => returned) Status.stub(:find_by_name).with(returned).and_return(returned_status) order.should_receive(:update_attributes).with(:status => returned_status) order.update_status end it "changes paid to shipped" do paid_status = Fabricate(:status, :name => paid) order.should_receive(:status).and_return(paid_status) shipped_status = Fabricate(:status, :name => shipped) Status.stub(:find_by_name).with(shipped).and_return(shipped_status) order.should_receive(:update_attributes).with(:status => shipped_status) order.update_status end end context "#total" do it "returns the total of all cart items" do item = Fabricate(:order_item) item2 = Fabricate(:order_item) order.should_receive(:order_items).and_return([item, item2]) order.total.should == Money.new(20000) end it "returns 0 if there are not cart items" do order.total.should == Money.new(0) end end describe "#remove_item" do context "when items exist in the order" do let(:order_item) { Fabricate(:order_item) } let(:order_item2) { Fabricate(:order_item) } let(:order_items) { [order_item, order_item2] } it "removes an item from the order" do order = Fabricate(:order, :order_items => order_items) order.order_items.count.should == 2 order.remove_item(order_item.id) order.order_items.count.should == 1 order.order_items.include?(order_item2).should == true end end end end
# -*- ruby -*- # This runs both the blog app and the object log viewer as separate # Sinatra apps in the same process require 'sinatra' require 'blog_app' require '../object_inspector/objectlog_app' disable :run set :environment, :development options = { :Port => 4444, :host => 'localhost' } map "/" do run BlogApp end map "/objectlog" do # Tell the ObjectLogApp where it is mounted. ObjectLogApp.script_name = "/objectlog" ObjectLogApp.main_app_url = "http://localhost:4444/" # A somewhat informed guess ObjectLogApp.main_object = "Maglev::PERSISTENT_ROOT[SimplePost]" run ObjectLogApp end
# typed: false # frozen_string_literal: true # This file was generated by GoReleaser. DO NOT EDIT. class Dojoctl < Formula desc "" homepage "" version "0.0.14" bottle :unneeded if OS.mac? && Hardware::CPU.intel? url "https://github.com/zengineDev/dojo/releases/download/v0.0.14/dojoctl_0.0.14_Darwin_x86_64.tar.gz" sha256 "a94d8d9112257f2dc4c4a3965d0b9303c7471560d65f5a4a68b20166ec64eb86" end if OS.mac? && Hardware::CPU.arm? url "https://github.com/zengineDev/dojo/releases/download/v0.0.14/dojoctl_0.0.14_Darwin_arm64.tar.gz" sha256 "ab751e9a0e62c43d74269099869ff249cb2327fb3b636a985ca25f370f8f5747" end if OS.linux? && Hardware::CPU.intel? url "https://github.com/zengineDev/dojo/releases/download/v0.0.14/dojoctl_0.0.14_Linux_x86_64.tar.gz" sha256 "d6453de4d2776e4fb70d6d49125380df3ff66e65713fbfa01ff31fc3e4206fe7" end if OS.linux? && Hardware::CPU.arm? && !Hardware::CPU.is_64_bit? url "https://github.com/zengineDev/dojo/releases/download/v0.0.14/dojoctl_0.0.14_Linux_armv6.tar.gz" sha256 "fb0b9c1b1492831b0162a21e846125786cd7aff84f7d8fed5d4b8f4d79ee1f46" end if OS.linux? && Hardware::CPU.arm? && Hardware::CPU.is_64_bit? url "https://github.com/zengineDev/dojo/releases/download/v0.0.14/dojoctl_0.0.14_Linux_arm64.tar.gz" sha256 "0af7ea702985a27e16c5f7e57f052e5209cb8d0ad4ebbde5f355d3175f2b9f64" end def install bin.install "dojoctl" end end
name 'dashing' maintainer 'Benbria' maintainer_email 'jwalton@benbria.ca' license 'MIT License' description 'Installs/Configures dashing - http://shopify.github.io/dashing/' long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) version '0.1.0'
class DbToolsExtension < Spree::Extension version "1.0" description "An extension to add a few useful database related rake tasks." url "http://github.com/eliotsykes/spree-db-tools" def self.require_gems(config) config.gem "sevenwire-forgery", :lib => "forgery", :source => "http://gems.github.com" end def activate Spree::Setup.class_eval do def self.change_password new.change_password end def change_password say "Change password for a user (press enter for defaults)." email = ask("User's email [spree@example.com]: ", String) do |q| q.echo = true q.validate = proc do |email| email = 'spree@example.com' if email.blank? return User.exists?(:email => email) end q.responses[:not_valid] = "Invalid e-mail. No user with this e-mail." q.whitespace = :strip end email = 'spree@example.com' if email.blank? user = User.find_by_login email say "Enter new password" password = prompt_for_admin_password user.update_attributes!(:password => password, :password_confirmation => password) say "Password updated for user '#{user.email}'" end end end end
require 'sinatra' get '/' do # hello @varaible_for_view = 'Hi! I am a variable. the @ at the beginning will make it accessible in the erb/view file.' @people = ["Jonathan", "Joel", "Jarrett"] erb :index, layout: :main end get '/form' do # code! @states = [] #create an array called states #create a hash key = ["PA","NY","TX","NC","SC"] #key value = ["Pennsylvania", "New York", "Texas", "North Carolina", "South Carolina"] #value 0.upto(4) do | s | #going to add each hash to our array state = {} #initializing state hash state[:id] = key[s] #adding ID state[:name] = value[s] #adding NAME @states << state #adding state hash to states array end @states.sort_by!{|state| state[:name]} #sorted alphabetically @params = {} erb :form, layout: :main end post '/form' do # code! @states = [] #create an array called states #create a hash key = ["PA","NY","TX","NC","SC"] #key value = ["Pennsylvania", "New York", "Texas", "North Carolina", "South Carolina"] #value 0.upto(4) do | s | #going to add each hash to our array state = {} #initializing state hash state[:id] = key[s] #adding ID state[:name] = value[s] #adding NAME @states << state #adding state hash to states array end @states.sort_by!{|state| state[:name]} #sorted alphabetically erb :form, layout: :main end get '/example' do # code! erb :example, layout: :main end post '/example' do # code! erb :example, layout: :main end
class RequestStatusesController < ApplicationController before_action :set_request_status, only: [:show, :update, :destroy] def index @request_statuses = RequestStatus.all render json: @request_statuses end def show render json: @request_status end def create @request_status = RequestStatus.new(request_status_params) if @request_status.save render json: @request_status, status: :created, location: @request_status else render json: @request_status.errors, status: :unprocessable_entity end end def update if @request_status.update(request_status_params) render json: @request_status else render json: @request_status.errors, status: :unprocessable_entity end end def destroy @request_status.destroy end private def set_request_status @request_status = RequestStatus.find(params[:id]) end def request_status_params params.require(:request_status).permit(:name) end end
def convert_seconds_to_years_and_months(age_in_seconds) @years_old = age_in_seconds / (60 * 60 * 24 * 365) @remaining_months = (age_in_seconds % (60 * 60 * 24 * 365) ) / ( 60 * 60 * 24 * 30 ) end def prints_age_in_years_and_months(age_in_seconds) puts "Being #{age_in_seconds} seconds old is equivalent to being #{@years_old} years and #{@remaining_months} months old." end ages_in_seconds = [ 979000000, 2158493738, 246144023, 1270166272, 1025600095, ] ages_in_seconds.each do |seconds| convert_seconds_to_years_and_months(seconds) prints_age_in_years_and_months(seconds) end
require 'rails_helper' RSpec.describe Project do let(:project){Project.new} let(:task){Task.new} it 'idenitifies a newly created project as done' do expect(project).to be_done end it 'detects that a project with a new task is not done' do project.tasks << task expect(project).to_not be_done end describe "estimates" do let(:project){Project.new} let(:done){Task.new( {size:2,completed_at: 1.day.ago})} let(:small_done){Task.new({size: 1,completed_at: 1.month.ago})} let(:small_not_done){Task.new({size: 1})} let(:large_not_done){Task.new({size: 4})} let(:large_done){Task.new({size: 4,completed_at: 1.day.ago})} before(:example) do project.tasks = [done,small_not_done,large_not_done,small_done,large_done] end #done counts 2, 4 = 6 #done not count = 1 #total_done = 7 #total_not_done = 5 #total 12 it "can calculate total size" do expect(project.total_size).to eq(12) end it "can calculate remaining size" do expect(project.remaining_size).to eq(5) end it 'knows its own completed task size of tasks completed within three weeks' do expect(project.completed_task_size).to eq(6) end it 'knows its own rate of completed tasks per day' do expect(project.completed_tasks_per_day).to eq(6.0/21.0) end it 'knows if its on schedule' do project.due_date = Time.current + 2.month expect(project).to be_on_schedule end it 'knows if its not on schedule' do project.due_date = Time.current + 1.day expect(project).to_not be_on_schedule end end end
class Profile::ResourcesController < Profile::ProfileController before_filter :set_resource, only: [:edit, :update] before_filter :set_current_user, only: [:create, :update] def index @resources = current_user.resources.recent end def new @resource = Resource.new authorize! :new, @resource @resource.assets.build @resource.new_organization = Organization.new end def create @resource = Resource.new(params[:resource]) authorize! :create, @resource @resource.status_id = Resource::STATUSES[:Suggested] @resource.users << current_user if @resource.save redirect_to profile_resources_path, notice: "Thank you for submitting a new resource. " + "We'll review and approve all additions before they get published" else render :new @resource.new_organization = Organization.new end end def edit authorize! :edit, @resource @resource.new_organization = Organization.new end def update authorize! :update, @resource if @resource.update_attributes(params[:resource]) @resource.clear_audiences if params[:resource][:audience_ids].blank? @resource.clear_boroughs if params[:resource][:borough_ids].blank? @resource.clear_languages if params[:resource][:language_ids].blank? @resource.clear_phases if params[:resource][:phase_ids].blank? @resource.clear_subjects if params[:resource][:subject_ids].blank? @resource.clear_subway_lines if params[:resource][:subway_line_ids].blank? @resource.clear_supports if params[:resource][:support_ids].blank? redirect_to profile_resources_path, notice: ("Your edits have been saved. View them here " + "<a href='#{resource_path(@resource)}'>#{@resource.name}</a>").html_safe else render :edit @resource.new_organization = Organization.new end end private def set_resource @resource = current_user.resources.find_by_permalink!(params[:id]) end end
module Recliner module AttributeMethods module Defaults extend ActiveSupport::Concern included do alias_method_chain :initialize, :defaults end def initialize_with_defaults(attributes={}, &block)#:nodoc: default_attributes.each do |property, default| write_attribute(property, default) end initialize_without_defaults(attributes, &block) end private def default_attributes result = {} properties.each do |name, property| result[name] = property.default_value(self) unless name == :rev end result end end end end
require "redis" class RedisSet attr_reader :name VERSION = "0.0.6" class InvalidNameException < StandardError; end; class InvalidRedisConfigException < StandardError; end; def initialize(name, redis_or_options = {}, more_options = {}) name = name.to_s if name.kind_of? Symbol raise InvalidNameException.new unless name.kind_of?(String) && name.size > 0 @name = name @redis = if redis_or_options.kind_of?(Redis) redis_or_options elsif redis_or_options.kind_of? Hash ::Redis.new redis_or_options elsif defined?(ActiveSupport::Cache::RedisStore) && redis_or_options.kind_of?(ActiveSupport::Cache::RedisStore) @pooled = redis_or_options.data.kind_of?(ConnectionPool) redis_or_options.data elsif defined?(ConnectionPool) && redis_or_options.kind_of?(ConnectionPool) @pooled = true redis_or_options else raise InvalidRedisConfigException.new end if more_options.kind_of?(Hash) && more_options[:expire] expire more_options[:expire] end end def add *values values = [values].flatten with{|redis| redis.sadd name, values} if values.size > 0 end alias push add def add_with_count value block_on_atomic_attempt { attempt_atomic_add_read_count value } end alias push_with_count add_with_count def remove *values values = [values].flatten with{|redis|redis.srem name, values} if values.size > 0 end def pop(amount = 1) with{|redis| redis.spop name, amount} end def include? value with{|redis| redis.sismember(name, value)} end def size with{|redis| redis.scard name} end alias count size def all with{|redis| redis.smembers name} end def intersection *sets sets = [sets].flatten if sets.size >= 1 sets = sets.map do |s| if s.kind_of?(self.class) s.name else s end end sets << name with{|redis| redis.sinter *sets } end end def scan cursor = 0, amount = 10, match = "*" with{|redis| redis.sscan name, cursor, :count => amount, :match => match} end def enumerator(slice_size = 10) cursor = 0 Enumerator.new do |yielder| loop do cursor, items = scan cursor, slice_size items.each do |item| yielder << item end raise StopIteration if cursor.to_i.zero? end end end def clear with{|redis| redis.del name} [] end alias flush clear def expire seconds with{|redis| redis.expire name, seconds.to_i} end private def attempt_atomic_add_read_count value attempt_atomic_write_read lambda { add value }, lambda { |multi, read_result| multi.scard name } end def block_on_atomic_attempt begin success, result = yield #puts "success is #{success} and result is #{result}" end while !success && result result.value end def attempt_atomic_write_read write_op, read_op success, write_result, read_result = false, nil, nil with do |redis| success = redis.watch(name) do write_result = write_op.call #if write_result redis.multi do |multi| read_result = read_op.call multi, write_result end #end end end [success, read_result] end def with(&block) if pooled? @redis.with(&block) else block.call(@redis) end end def pooled? !!@pooled end end
class User < ApplicationRecord has_secure_password validates_presence_of :name, :email, :password_digest validates_uniqueness_of :email validates_format_of :email, with: /\A[^@]+@([^@\.]+\.)+[^@\.]+\z/ def is_admin? id == 1 end class << self def admin first end end end