repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
JulianNicholls/Complete-Finance-Tracker
app/models/stock.rb
# Model for stock, with several class functions class Stock < ActiveRecord::Base has_many :user_stocks has_many :users, through: :user_stocks class << self def new_from_lookup(ticker) looked_up = StockTicker.new(ticker) name = looked_up.name return nil unless name new_stock = new(ticker: looked_up.symbol, name: name) new_stock.last_price = new_stock.price new_stock end def find_by_ticker(ticker) where(ticker: ticker).first end end def price StockTicker.new(ticker).price end end # Shim for stock_quote gem class StockTicker attr_reader :symbol def initialize(symbol) @symbol = symbol @ticker = StockQuote::Stock.quote(symbol) end def price return "#{closing} (Closing)" if closing return "#{opening} (Opening)" if opening 'Unavailable' end def name @ticker.name end private def closing @ticker.close end def opening @ticker.open end end
JulianNicholls/Complete-Finance-Tracker
app/models/user.rb
# Model for User class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable # :recoverable devise :database_authenticatable, :registerable, :rememberable, :trackable, :validatable has_many :user_stocks has_many :stocks, through: :user_stocks has_many :friendships has_many :friends, through: :friendships class << self def search(param) return user.none if param.blank? param.strip! param.downcase! (first_name_matches(param) + last_name_matches(param) + email_matches(param)).uniq end def first_name_matches(param) matches('first_name', param) end def last_name_matches(param) matches('last_name', param) end def email_matches(param) matches('email', param) end def matches(field_name, param) where("LOWER(#{field_name}) LIKE ?", "%#{param}%") end end def full_name "#{first_name} #{last_name}".strip end def can_add_stock?(ticker) under_stock_limit? && !stock_already_added?(ticker) end def under_stock_limit? user_stocks.count < 10 end def stock_already_added?(ticker) stock = Stock.find_by_ticker ticker return false unless stock user_stocks.where(stock_id: stock.id).exists? end def not_friends_with?(other) friendships.where(friend_id: other.id).count < 1 end def except_current_user(users) users.reject { |user| user.id == self.id } end end
JulianNicholls/Complete-Finance-Tracker
app/controllers/welcome_controller.rb
<reponame>JulianNicholls/Complete-Finance-Tracker # Controller for home page class WelcomeController < ApplicationController def index end end
JulianNicholls/Complete-Finance-Tracker
app/models/user_stock.rb
<gh_stars>1-10 # Model for Tracked stock for User class UserStock < ActiveRecord::Base belongs_to :user belongs_to :stock end
JulianNicholls/Complete-Finance-Tracker
app/helpers/application_helper.rb
# General helpers for views module ApplicationHelper end
JulianNicholls/Complete-Finance-Tracker
app/controllers/users_controller.rb
# Controller fur users class UsersController < ApplicationController def show @user = User.find params[:id] @user_stocks = @user.stocks end def my_portfolio @user = current_user @user_stocks = @user.stocks end def my_friends @friends = current_user.friends end def search @users = User.search params[:search_param] if @users @users = current_user.except_current_user @users render partial: 'friends/lookup' else render status: :not_found, nothing: true end end def add_friend @friend = User.find params[:friend] current_user.friendships.build friend: @friend if current_user.save redirect_to my_friends_path, notice: 'That friend has been added.' else redirect_to my_friends_path, flash[:error] = 'There was an error with adding that friend.' end end end
danmorrisonNZ/Flash-Card-Solo
app/models/user.rb
<reponame>danmorrisonNZ/Flash-Card-Solo<filename>app/models/user.rb class User < ActiveRecord::Base has_many :decks def self.authenticate(username, password) User.find_by(user_name: username, password: password) end end
danmorrisonNZ/Flash-Card-Solo
db/migrate/20150212184802_create_cards.rb
<filename>db/migrate/20150212184802_create_cards.rb class CreateCards < ActiveRecord::Migration def change create_table :cards do |t| t.belongs_to :deck, index:true t.integer :card_number t.string :card_type t.string :question t.string :answer t.timestamps end end end
danmorrisonNZ/Flash-Card-Solo
app/controllers/index.rb
get '/' do if session[:current_user] redirect '/home' else redirect '/login' end end get '/login' do @error = session[:error] erb :login end post '/login' do @current_user = User.authenticate(params[:username],params[:password]) if @current_user session[:error] = nil session[:current_user] = @current_user else session[:error] = "Incorrect user name or password, please try again." end redirect '/' end post '/signup' do @current_user = User.create(user_name: params[:username], first_name: params[:firstname] , last_name: params[:lastname] , email: params[:email] , password: params[:password]) if @current_user session[:error] = nil session[:current_user] = @current_user else session[:error] = "There was an error while logining in" end redirect '/' end get '/home' do @user = session[:current_user] @deck = Deck.where(user_id: @user.id) erb :index end get '/home/:id' do @user= User.find_by(id: params[:id]) @deck = Deck.find_by(user_id: params[:id]) erb :show end get '/play/:deckname' do @error = session[:error] @deck = Deck.find_by(deck_name: params[:deckname]) @cards = Card.where(deck_id: @deck.id) @current_card = @cards.find_by(id: 1) if @current_card session[:error] = nil session[:card] = @current_card else session[:error] = "No cards yo!" end erb :showdeck end get '/play/answer' do current_card = session[:card] if params[:answer] == current_card "hurray" else session[:card] end end get '/logout' do session.clear redirect '/' end
danmorrisonNZ/Flash-Card-Solo
app/models/deck.rb
<filename>app/models/deck.rb class Deck < ActiveRecord::Base has_many :cards belongs_to :users end
danmorrisonNZ/Flash-Card-Solo
app/models/card.rb
<gh_stars>0 class Card < ActiveRecord::Base belongs_to :decks def answer?(answer) if answer == Card.answer puts "correct!" else puts "incorrect!" end end end
danmorrisonNZ/Flash-Card-Solo
db/seeds.rb
Card.destroy_all card_no = 0 lines = File.readlines("db/question_answer_database_lines.txt") total_lines = lines.length/2 until lines.empty? Card.create(deck_id: 1 ,card_number: card_no +1, card_type: "eneumerable", answer:lines.shift.chomp, question:lines.shift.chomp) card_no +=1 end Deck.create(id:1 , user_id: 1, deck_name: "eneumerable", card_count: total_lines) User.create( user_name:"danmorrisonNZ", first_name: "Dan", last_name:"Morrison", email: "<EMAIL>", password:"<PASSWORD>")
danmorrisonNZ/Flash-Card-Solo
db/migrate/20150212184753_create_decks.rb
<filename>db/migrate/20150212184753_create_decks.rb class CreateDecks < ActiveRecord::Migration def change create_table :decks do |t| t.belongs_to :user, index:true t.string :deck_name t.integer :card_count t.timestamps end end end
danmorrisonNZ/Flash-Card-Solo
number.rb
even_numbers = [2,4,6,8,10,12,14,16,18,20] odd_numbers = [1,3,5,7,9,11,13,15,17,19] prime_numbers = [1,3,5,7,11,13,17,19]
krys2fa/members-only
test/controllers/post_controller_test.rb
<gh_stars>1-10 require 'test_helper' class PostControllerTest < ActionDispatch::IntegrationTest test 'should get create' do get post_create_url assert_response :success end test 'should get new' do get post_new_url assert_response :success end test 'should get index' do get post_index_url assert_response :success end end
flant/dappdeps-base
omnibus/config/projects/dappdeps-base.rb
name 'dappdeps-base' maintainer '<NAME>' homepage 'https://github.com/flant/dappdeps-base' license 'MIT' license_file 'LICENSE.txt' DOCKER_IMAGE_VERSION = "0.2.2" install_dir "/.dapp/deps/base/#{DOCKER_IMAGE_VERSION}" build_version DOCKER_IMAGE_VERSION build_iteration 1 dependency "dappdeps-base"
ProofFactorLLC/zerobounce
spec/zerobounce/response_spec.rb
<reponame>ProofFactorLLC/zerobounce # frozen_string_literal: true RSpec.describe Zerobounce::Response do let(:response) { spy } let(:request) { spy } describe '#status' do before { allow(response).to receive(:body).and_return(status: 'DoNotMail') } it 'returns a symbol' do expect(described_class.new(response, request).status).to be_a(Symbol) end describe 'API V1' do before { Zerobounce.config.api_version = 'v1' } it 'converts camelcase to snakecase' do expect(described_class.new(response, request).status).to eq(:do_not_mail) end end end describe '#sub_status' do before { allow(response).to receive(:body).and_return(sub_status: 'global_suppression') } it 'returns a symbol' do expect(described_class.new(response, request).sub_status).to be_a(Symbol) end end describe '#inspect' do it 'returns a string' do expect(described_class.new(response, request).inspect).to be_a(String) end end describe '#processed_at' do before { allow(response).to receive(:body).and_return(processedat: Time.now.to_s) } it 'returns a time object' do expect(described_class.new(response, request).processed_at).to be_a(Time) end end describe '#creation_date' do before { allow(response).to receive(:body).and_return(creationdate: Time.now.to_s) } it 'returns a time object' do expect(described_class.new(response, request).creation_date).to be_a(Time) end end describe '#valid?' do before { allow(response).to receive(:body).and_return(status: 'DoNotMail') } it 'can change what a valid email is' do expect { Zerobounce.config.valid_statuses = %i[do_not_mail] }.to( change { described_class.new(response, request).valid? }.from(false).to(true) ) end end describe '#to_h' do before do allow(response).to receive(:body).and_return(processedat: Time.now.to_s, creationdate: Time.now.to_s) end it 'does not return request' do expect(described_class.new(response, request).to_h).not_to include(request: anything) end it 'does not return response' do expect(described_class.new(response, request).to_h).not_to include(response: anything) end it 'does not return inspect' do expect(described_class.new(response, request).to_h).not_to include(inspect: anything) end it 'does not return to_h' do expect(described_class.new(response, request).to_h).not_to include(to_h: anything) end it 'returns a hash' do expect(described_class.new(response, request).to_h).to be_a(Hash) end end end
ProofFactorLLC/zerobounce
spec/zerobounce_spec.rb
<reponame>ProofFactorLLC/zerobounce<filename>spec/zerobounce_spec.rb # frozen_string_literal: true RSpec.describe Zerobounce do it 'has a version number' do expect(Zerobounce::VERSION).not_to be_nil end describe '.configure' do let(:apikey) { [*('a'..'z')].sample(32).join } it 'yields the configuration' do expect { |b| described_class.configure(&b) }.to yield_with_args(Zerobounce::Configuration) end it 'sets the api key in configure block' do described_class.configure { |config| config.apikey = apikey } expect(described_class.configuration.apikey).to eq(apikey) end end describe '.configuration' do it 'returns the same configuration instance' do expect(described_class.configuration).to equal(described_class.configuration) end end describe '.validate' do let(:request) { instance_spy(Zerobounce::Request::V1Request) } before do allow(request).to receive(:validate) allow(request).to receive(:validate_with_ip) allow(Zerobounce::Request).to receive(:new).and_return(request) end it 'calls #validate on request' do described_class.validate(email: '<EMAIL>') expect(request).to have_received(:validate).with(email: '<EMAIL>') end end describe '.valid?' do let(:response) { instance_spy(Zerobounce::Response) } before do allow(response).to receive(:valid?).and_return(true) req = instance_double(Zerobounce::Request::V1Request) allow(Zerobounce::Request).to receive(:new).and_return(req) allow(req).to receive(:validate).and_return(response) end it 'calls #valid? on response' do described_class.valid?('<EMAIL>') expect(response).to have_received(:valid?) end end describe '.invalid?' do let(:response) { instance_spy(Zerobounce::Response) } before do allow(response).to receive(:invalid?).and_return(false) req = instance_double(Zerobounce::Request::V1Request) allow(Zerobounce::Request).to receive(:new).and_return(req) allow(req).to receive(:validate).and_return(response) end it 'calls #valid? on response' do described_class.invalid?('<EMAIL>') expect(response).to have_received(:invalid?) end end describe '.credits' do let(:request) { instance_spy(Zerobounce::Request) } before do allow(request).to receive(:credits) allow(Zerobounce::Request).to receive(:new).and_return(request) end it 'calls #credits on request' do described_class.credits expect(request).to have_received(:credits) end end end
ProofFactorLLC/zerobounce
spec/support/reset_config.rb
<gh_stars>1-10 # frozen_string_literal: true RSpec.configure do |config| config.after do Zerobounce.instance_variable_set(:@configuration, Zerobounce::Configuration.new) end end
ProofFactorLLC/zerobounce
spec/zerobounce/configuration_spec.rb
# frozen_string_literal: true RSpec.describe Zerobounce::Configuration do it 'has correct attributes' do expect(described_class.new).to have_attributes( apikey: be_nil, host: be_a(String), headers: be_a(Hash), middleware: be_a(Proc), valid_statuses: be_an(Array) ) end describe '#apikey', mock_env: true do before { ENV['ZEROBOUNCE_API_KEY'] = 'foobar' } it 'uses the environment variable "ZEROBOUNCE_API_KEY" by default' do expect(described_class.new.apikey).to eq('foobar') end end describe '#middleware' do let(:builder) { spy } before do allow(builder).to receive(:response) allow(builder).to receive(:use) allow(builder).to receive(:adapter) end it 'uses json parser for response middleware' do described_class.new.middleware.call(builder) expect(builder).to have_received(:response).with(:json, Hash) end it 'uses the RaiseError class' do described_class.new.middleware.call(builder) expect(builder).to have_received(:use).with(Zerobounce::Middleware::RaiseError) end it 'uses Faraday default adapter' do described_class.new.middleware.call(builder) expect(builder).to have_received(:adapter).with(Faraday.default_adapter) end end end
ProofFactorLLC/zerobounce
spec/zerobounce/middleware/raise_error_spec.rb
# frozen_string_literal: true RSpec.describe Zerobounce::Middleware::RaiseError do describe '#on_complete' do context 'when response contains an error' do let(:env) { { status: 500 } } it 'raises an error' do expect { described_class.new.on_complete(env) }.to raise_error(Zerobounce::InternalServerError) end end context 'when response does not contain and error' do let(:env) { { status: 200 } } it 'does not return an error' do expect { described_class.new.on_complete(env) }.not_to raise_error end it 'returns nil' do expect(described_class.new.on_complete(env)).to be_nil end end end end
ProofFactorLLC/zerobounce
lib/zerobounce/request/v1_request.rb
<reponame>ProofFactorLLC/zerobounce # frozen_string_literal: true module Zerobounce class Request # Request methods specific to V1 of the API. module V1Request # Valid v1 get query params VALID_GET_PARAMS = %i[apikey ipaddress email].freeze # Validate the email address. # # @param [Hash] params # @option params [String] :email # @option params [String] :ip_address # @option params [String] :apikey # @return [Zerobounce::Response] def validate(params) if params.key?(:ipaddress) || params.key?(:ip_address) validate_with_ip(params) else Response.new(get('validate', params), self) end end # Validate the email address and get geoip info for the IP. # # @param [Hash] params # @option params [String] :email # @option params [String] :ip_address # @option params [String] :apikey # @return [Zerobounce::Response] def validate_with_ip(params) Response.new(get('validatewithip', params), self) end private # @param [Hash] params # @return [Hash] def get_params(params) params[:ipaddress] = params.delete(:ip_address) if params.key?(:ip_address) # normalize ipaddress key params[:apikey] = params.delete(:api_key) if params.key?(:api_key) # normalize apikey param { apikey: Zerobounce.config.apikey }.merge(params.select { |k, _| VALID_GET_PARAMS.include?(k) }) end end end end
ProofFactorLLC/zerobounce
spec/simplecov_env.rb
<filename>spec/simplecov_env.rb # frozen_string_literal: true require 'simplecov' module SimpleCovEnv def self.start! configure_profile SimpleCov.start end def self.configure_profile formatters = [SimpleCov::Formatter::HTMLFormatter] SimpleCov.configure do formatter SimpleCov::Formatter::MultiFormatter.new(formatters) # Don't run coverage on the spec folder. add_filter 'spec' # save to CircleCI's artifacts directory if we're on CircleCI coverage_dir(File.join(ENV['CIRCLE_ARTIFACTS'], 'coverage')) if ENV['CIRCLE_ARTIFACTS'] end end end
ProofFactorLLC/zerobounce
lib/zerobounce/response/v2_response.rb
# frozen_string_literal: true module Zerobounce class Response # V2 specific methods for the API. module V2Response # Deliverability status # # @see https://www.zerobounce.net/docs/email-validation-api-quickstart/#status_codes__v2__ # # Possible values: # :valid # :invalid # :catch_all # :unknown # :spamtrap # :abuse # :do_not_mail # # @return [Symbol] The status as a +Symbol+. def status @status ||= @body[:status].to_s.empty? ? nil : @body[:status].tr('-', '_').to_sym end # @return [Symbol, nil] def sub_status @sub_status ||= @body[:sub_status].to_s.empty? ? nil : @body[:sub_status].to_sym end # @return [Integer] def domain_age_days @domain_age_days ||= @body[:domain_age_days].to_i end # The SMTP Provider of the email. # # @return [String, nil] def smtp_provider @smtp_provider ||= @body[:smtp_provider] end # @return [String, nil] def did_you_mean @did_you_mean ||= @body[:did_you_mean] end # The preferred MX record of the domain. # # @return [String, nil] def mx_record @mx_record ||= @body[:mx_record] end # The UTC time the email was validated. # # @return [Time, nil] def processed_at @processed_at ||= @body[:processed_at] && Time.parse("#{@body[:processed_at]} UTC") end # If the email comes from a free provider. # # @return [Boolean] def free_email? @free_email ||= @body[:free_email] || false end # If the email domain is disposable, which are usually temporary email addresses. # # These are temporary emails created for the sole purpose to sign up to websites without giving their real # email address. These emails are short lived from 15 minutes to around 6 months. # # @note If you have valid emails with this flag set to +true+, you shouldn't email them. # # @return [Boolean] def disposable? @disposable ||= sub_status == :disposable end # These domains are known for abuse, spam, or are bot created. # # @note If you have a valid email with this flag set to +true+, you shouldn't email them. # # @return [Boolean] def toxic? @toxic ||= sub_status == :toxic end # Does the domain have an MX record. # # @return [Boolean] def mx_found? @mx_found ||= @body[:mx_found] == 'true' end end end end
ProofFactorLLC/zerobounce
spec/support/mock_env.rb
# frozen_string_literal: true RSpec.configure do |config| config.around(mock_env: true) do |example| original_env = ENV.to_h begin example.run ensure ENV.clear ENV.update(original_env) end end end
ProofFactorLLC/zerobounce
lib/zerobounce/response/v1_response.rb
<filename>lib/zerobounce/response/v1_response.rb<gh_stars>1-10 # frozen_string_literal: true module Zerobounce class Response # V1 specific methods for the API. module V1Response # Deliverability status # # Possible values: # :valid # :invalid # :catch_all # :unknown # :spamtrap # :abuse # :do_not_mail # # @return [Symbol] The status as a +Symbol+. def status @status ||= @body[:status].to_s.empty? ? nil : underscore(@body[:status]).to_sym end # A more detailed status # # Possible values: # :antispam_system # :greylisted # :mail_server_temporary_error # :forcible_disconnect # :mail_server_did_not_respond # :timeout_exceeded # :failed_smtp_connection # :mailbox_quota_exceeded # :exception_occurred # :possible_traps # :role_based # :global_suppression # :mailbox_not_found # :no_dns_entries # :failed_syntax_check # :possible_typo # :unroutable_ip_address # :leading_period_removed # :does_not_accept_mail # :alias_address # :unknown # # @return [Symbol] The sub_status as a +Symbol+. def sub_status @sub_status ||= @body[:sub_status].to_s.empty? ? nil : underscore(@body[:sub_status]).to_sym end # If the email domain is disposable, which are usually temporary email addresses. # # These are temporary emails created for the sole purpose to sign up to websites without giving their real # email address. These emails are short lived from 15 minutes to around 6 months. # # @note If you have valid emails with this flag set to +true+, you shouldn't email them. # # @return [Boolean] def disposable? @disposable ||= @body[:disposable] || false end # These domains are known for abuse, spam, or are bot created. # # @note If you have a valid email with this flag set to +true+, you shouldn't email them. # # @return [Boolean] def toxic? @toxic ||= @body[:toxic] || false end # The location of the owner of the email when available. # # @return [String, nil] def location @location ||= @body[:location] end # The UTC time the email was validated. # # @return [Time, nil] def processed_at @processed_at ||= @body[:processedat] && Time.parse("#{@body[:processedat]} UTC") end # The creation date of the email when available. # # @return [Time, nil] def creation_date @creation_date ||= @body[:creationdate] && Time.parse("#{@body[:creationdate]} UTC") end private # @param [String] word # @return [String] def underscore(word) word.gsub(/([a-z\d])([A-Z])/, '\1_\2').downcase.tr('-', '_') end end end end
ProofFactorLLC/zerobounce
lib/zerobounce/configuration.rb
<gh_stars>1-10 # frozen_string_literal: true require 'faraday' require 'faraday_middleware' require 'zerobounce/middleware/raise_error' module Zerobounce # Configuration object for Zerobounce. # # @author <NAME> # # @attr [String] host # The Zerobounce API host. # # @attr [Hash] headers # Headers to use in all requests. # # @attr [String] apikey # A Zerobounce API key. # # @attr [Proc] middleware # The middleware used by Faraday for each request. # # @note If you modify the default make sure to add middleware to parse # the response as json and symbolize the keys. # # @attr [String] api_version # The version of the API to use. # # @attr [Array<Symbol>] valid_statues # The statuses that are considered valid by {Response#valid?}. class Configuration attr_accessor :host attr_accessor :headers attr_accessor :apikey attr_accessor :middleware attr_accessor :api_version attr_accessor :valid_statuses def initialize self.host = 'https://api.zerobounce.net' self.apikey = ENV['ZEROBOUNCE_API_KEY'] self.api_version = 'v2' self.valid_statuses = %i[valid catch_all] self.headers = { user_agent: "ZerobounceRubyGem/#{Zerobounce::VERSION}" } self.middleware = proc do |builder| builder.response(:json, content_type: /\bjson$/, parser_options: { symbolize_names: true }) builder.response(:logger) { |l| l.filter(/(api_?key=)(\w+)/, '\1[REMOVED]') } if ENV['ZEROBOUNCE_API_DEBUG'] builder.use(Zerobounce::Middleware::RaiseError) builder.adapter(Faraday.default_adapter) end end end end
ProofFactorLLC/zerobounce
spec/zerobounce/request_spec.rb
# frozen_string_literal: true RSpec.describe Zerobounce::Request do describe '.new' do context 'when middleware in params' do let(:middleware) { proc {} } it 'uses the middleware' do expect(described_class.new(middleware: middleware).middleware).to be(middleware) end end context 'when middleware not in params' do it 'uses Zerobounce::Configuration#middleware' do expect(described_class.new.middleware).to be(Zerobounce.config.middleware) end end context 'when headers in params' do let(:headers) { { user_agent: 'foobar' } } it 'uses the headers' do expect(described_class.new(headers: headers).headers).to be(headers) end end context 'when headers not in params' do it 'uses Zerobounce::Configuration#headers' do expect(described_class.new.headers).to be(Zerobounce.config.headers) end end context 'when host in params' do let(:host) { 'http://example.com' } it 'uses the host' do expect(described_class.new(host: host).host).to be(host) end end context 'when host not in params' do it 'uses Zerobounce::Configuration#host' do expect(described_class.new.host).to be(Zerobounce.config.host) end end end describe 'API V1' do before { Zerobounce.config.api_version = 'v1' } describe '#validate_with_ip' do before do Zerobounce.config.middleware = proc do |f| f.adapter(:test) { |stub| stub.get('/v1/validatewithip') { |_| [200, {}, ''] } } end end it 'returns a response' do params = { email: '<EMAIL>', ip_address: '127.0.0.1' } expect(described_class.new.validate_with_ip(params)).to be_a(Zerobounce::Response) end end describe '#validate' do context 'with ip_address' do before do Zerobounce.config.middleware = proc do |f| f.adapter(:test) { |stub| stub.get('/v1/validatewithip') { |_| [200, {}, ''] } } end end it 'returns a response' do expect(described_class.new.validate(email: '<EMAIL>', ip_address: '127.0.0.1')).to( be_a(Zerobounce::Response) ) end end context 'without ip_address' do before do Zerobounce.config.middleware = proc do |f| f.adapter(:test) { |stub| stub.get('/v1/validate') { |_| [200, {}, {}] } } end end it 'returns a response' do expect(described_class.new.validate(email: '<EMAIL>')).to be_a(Zerobounce::Response) end end end describe '#credits' do before do Zerobounce.config.middleware = proc do |f| f.adapter(:test) { |stub| stub.get('/v1/getcredits') { |_| [200, {}, { Credits: '1' }] } } end end it 'returns an integer' do expect(described_class.new.credits).to be_an(Integer) end end end describe 'API V2' do before { Zerobounce.config.api_version = 'v2' } describe '#validate' do before do Zerobounce.config.middleware = proc do |f| f.adapter(:test) { |stub| stub.get('/v2/validate') { |_| [200, {}, ''] } } end end it 'returns a response' do expect(described_class.new.validate(email: '<EMAIL>')).to be_a(Zerobounce::Response) end end describe '#credits' do before do Zerobounce.config.middleware = proc do |f| f.adapter(:test) { |stub| stub.get('/v2/getcredits') { |_| [200, {}, { Credits: '1' }] } } end end it 'returns an integer' do expect(described_class.new.credits).to be_an(Integer) end end end end
ProofFactorLLC/zerobounce
lib/zerobounce/request.rb
# frozen_string_literal: true require 'faraday' require 'zerobounce/request/v1_request' require 'zerobounce/request/v2_request' module Zerobounce # Sends the HTTP request. # # @author <NAME> # # @attr_reader [String] host # The host to send the request to. # # @attr_reader [Hash] headers # The headers used for the request. # # @attr_reader [Proc] middleware # Faraday middleware used for the request. class Request attr_reader :host attr_reader :headers attr_reader :middleware attr_reader :api_version # Set instance variables and extends the correct Zerobounce::Request # # @param [Hash] params # @option params [String] :middleware default: {Configuration#middleware} {include:#middleware} # @option params [String] :headers default: {Configuration#headers} {include:#headers} # @option params [String] :host default: {Configuration#host} {include:#host} # @option params [String] :api_version default: {Configuration#api_version} {include:#api_version} def initialize(params={}) @middleware = params[:middleware] || Zerobounce.config.middleware @headers = params[:headers] || Zerobounce.config.headers @host = params[:host] || Zerobounce.config.host @api_version = params[:api_version] || Zerobounce.config.api_version case api_version when 'v2' extend(V2Request) else extend(V1Request) end end # Get the number of remaining credits on the account. # # @param [Hash] params # @option params [String] :apikey # @return [Integer] A value of -1 can mean the API is invalid. def credits(params={}) get('getcredits', params).body[:Credits].to_i end private # Sends a GET request. # # @param [Hash] params # @param [String] path # @return [Zerobounce::Response] def get(path, params) conn.get(path, get_params(params)) end # @return [Faraday::Connection] def conn @conn ||= Faraday.new("#{host}/#{api_version}", headers: headers, &middleware) end end end
ProofFactorLLC/zerobounce
lib/zerobounce/request/v2_request.rb
# frozen_string_literal: true module Zerobounce class Request # Request methods specific to V2 of the API. module V2Request # Valid v2 query params VALID_GET_PARAMS = %i[api_key ip_address email].freeze # Validate the email address. # # @param [Hash] params # @option params [String] :email # @option params [String] :ip_address # @option params [String] :api_key # @return [Zerobounce::Response] def validate(params) Response.new(get('validate', params), self) end private # @param [Hash] params # @return [Hash] def get_params(params) params[:ip_address] ||= '' # ip_address must be in query string params[:api_key] = params.delete(:apikey) if params.key?(:apikey) # normalize api_key param { api_key: Zerobounce.config.apikey }.merge(params.select { |k, _| VALID_GET_PARAMS.include?(k) }) end end end end
ProofFactorLLC/zerobounce
lib/zerobounce.rb
<filename>lib/zerobounce.rb # frozen_string_literal: true require 'zerobounce/error' require 'zerobounce/version' require 'zerobounce/request' require 'zerobounce/response' require 'zerobounce/configuration' # Validate an email address with Zerobounce.net module Zerobounce # @author <NAME> class << self attr_writer :configuration # Zerobounce configuration # # @return [Zerobounce::Configuration] def configuration @configuration ||= Configuration.new end alias config configuration # Configure Zerobounce inside a block. # # @example # Zerobounce.configure do |config| # config.apikey = 'api-key' # end # # @yieldparam [Zerobounce::Configuration] config def configure yield configuration end # Validates the email address and gets geoip information for an IP if provided. # # @param [Hash] params # @option params [String] :email The email address to validate. # @option params [String] :ip_address An IP address, :ipaddress also works. # @option params [String] :apikey Use a different API key for this request. # @option params [String] :host Use a different host for this request. # @option params [String] :headers Use different headers for this request. # @option params [Proc] :middleware Use different middleware for this request. # @return [Zerobounce::Response] def validate(params) Request.new(params).validate(params) end # Get the number of remaining credits on the account. # # @param [Hash] params # @option params [String] :apikey Use a different API key for this request. # @option params [String] :host Use a different host for this request. # @option params [String] :headers Use different headers for this request. # @option params [Proc] :middleware Use different middleware for this request. # @return [Integer] def credits(params={}) Request.new(params).credits(params) end # Convenience method for checking if an email address is valid. # # @param [String] email # @param [Hash] params # @return [Boolean] def valid?(email, params={}) validate(params.merge(email: email)).valid? end # Convenience method for checking if an email address is invalid. # # @param [String] email # @param [Hash] params # @return [Boolean] def invalid?(email, params={}) validate(params.merge(email: email)).invalid? end end end
ProofFactorLLC/zerobounce
lib/zerobounce/middleware/raise_error.rb
<filename>lib/zerobounce/middleware/raise_error.rb<gh_stars>1-10 # frozen_string_literal: true require 'zerobounce/error' module Zerobounce # Faraday middleware. module Middleware # Raises an error if the response wasn't successful. # # @author <NAME> class RaiseError < Faraday::Response::Middleware # Check for errors after the response has finished. # # @param [Hash] env # @raise [Error] def on_complete(env) if (error = Zerobounce::Error.from_response(env)) # rubocop:disable Style/GuardClause raise error end end end end end
ProofFactorLLC/zerobounce
spec/zerobounce/error_spec.rb
# frozen_string_literal: true RSpec.describe Zerobounce::Error do describe '.from_response' do context 'when status is 500' do let(:env) { { status: 500 } } it 'returns InternalServerError error' do expect(described_class.from_response(env)).to be_a(Zerobounce::InternalServerError) end context 'when body starts with Missing parameter' do before { env[:body] = 'Missing parameter' } it 'returns MissingParameter error' do expect(described_class.from_response(env)).to be_a(Zerobounce::MissingParameter) end end end context 'when status is 200' do let(:env) { { status: 200 } } it 'returns nil' do expect(described_class.from_response(env)).to be_nil end context 'when body looks like an error' do # The Zerobounce body contains a space after the `:` before { env[:body] = '{"error": "Invalid API Key or your account ran out of credits"}' } it 'returns ApiError' do expect(described_class.from_response(env)).to be_a(Zerobounce::ApiError) end end end end describe '#message' do context 'when status is 500' do let(:env) { { status: 500, body: 'error' } } it 'uses the body for the message' do expect(described_class.from_response(env).message).to eq('error') end end context 'when body looks like an error' do let(:error_message) { 'Invalid API Key or your account ran out of credits' } let(:env) { { status: 200, body: JSON.dump(error: error_message) } } it 'parses the json to get error message' do expect(described_class.from_response(env).message).to eq(error_message) end end end end
neeraji2it/sharetribe
app/models/category.rb
# == Schema Information # # Table name: categories # # id :integer not null, primary key # parent_id :integer # icon :string(255) # created_at :datetime # updated_at :datetime # community_id :integer # sort_priority :integer # url :string(255) # # Indexes # # index_categories_on_community_id (community_id) # index_categories_on_parent_id (parent_id) # index_categories_on_url (url) # class Category < ActiveRecord::Base attr_accessible( :community_id, :parent_id, :translations, :translation_attributes, :sort_priority, :url, :basename ) attr_accessor :basename has_many :subcategories, -> { order("sort_priority") }, :class_name => "Category", :foreign_key => "parent_id", :dependent => :destroy # children is a more generic alias for sub categories, used in classification.rb has_many :children, -> { order("sort_priority") }, :class_name => "Category", :foreign_key => "parent_id" belongs_to :parent, :class_name => "Category" has_many :listings has_many :translations, :class_name => "CategoryTranslation", :dependent => :destroy has_and_belongs_to_many :listing_shapes, -> { order("sort_priority") }, join_table: "category_listing_shapes" has_many :category_custom_fields, :dependent => :destroy has_many :custom_fields, -> { order("sort_priority") }, :through => :category_custom_fields belongs_to :community before_save :uniq_url before_destroy :can_destroy? def translation_attributes=(attributes) build_attrs = attributes.map { |locale, values| { locale: locale, values: values } } build_attrs.each do |translation| if existing_translation = translations.find_by_locale(translation[:locale]) existing_translation.update_attributes(translation[:values]) else translations.build(translation[:values].merge({:locale => translation[:locale]})) end end end def to_param url end def url_source basename || Maybe(default_translation_without_cache).name.or_else("category") end def default_translation_without_cache (translations.find { |translation| translation.locale == community.default_locale } || translations.first) end # TODO this should be done on service layer def uniq_url current_url = Maybe(url_source).to_url.or_else("noname") if new_record? || url != current_url blacklist = ['new', 'all'] base_url = current_url categories = Category.where(community_id: community_id) i = 1 while blacklist.include?(current_url) || categories.find { |c| c.url == current_url && c.id != id }.present? do current_url = "#{base_url}#{i}" i += 1 end self.url = current_url end end def display_name(locale) TranslationCache.new(self, :translations).translate(locale, :name) end def has_own_or_subcategory_listings? listings.count > 0 || subcategories.any? { |subcategory| !subcategory.listings.empty? } end def has_subcategories? subcategories.count > 0 end def has_own_or_subcategory_custom_fields? custom_fields.count > 0 || subcategories.any? { |subcategory| !subcategory.custom_fields.empty? } end def subcategory_ids subcategories.collect(&:id) end def own_and_subcategory_ids [id].concat(subcategory_ids) end def is_subcategory? !parent_id.nil? end def can_destroy? is_subcategory? || community.top_level_categories.count > 1 end def remove_needs_caution? has_own_or_subcategory_listings? or has_subcategories? end def own_and_subcategory_listings Listing.find_by_category_and_subcategory(self) end def own_and_subcategory_custom_fields CategoryCustomField.find_by_category_and_subcategory(self).includes(:custom_field).collect(&:custom_field) end def with_all_children # first add self child_array = [self] # Then add children with their children too children.each do |child| child_array << child.with_all_children end return child_array.flatten end def icon_name return icon if ApplicationHelper.icon_specified?(icon) return parent.icon_name if parent return "other" end def self.find_by_url_or_id(url_or_id) self.find_by_url(url_or_id) || self.find_by_id(url_or_id) end end
neeraji2it/sharetribe
app/models/paypal_account.rb
<filename>app/models/paypal_account.rb<gh_stars>0 # == Schema Information # # Table name: paypal_accounts # # id :integer not null, primary key # person_id :string(255) # community_id :integer # email :string(255) # payer_id :string(255) # created_at :datetime # updated_at :datetime # active :boolean default(FALSE) # # Indexes # # index_paypal_accounts_on_community_id (community_id) # index_paypal_accounts_on_payer_id (payer_id) # index_paypal_accounts_on_person_id (person_id) # class PaypalAccount < ActiveRecord::Base attr_accessible :email, :payer_id, :person_id, :community_id, :active belongs_to :person belongs_to :community has_one :order_permission, dependent: :destroy has_one :billing_agreement, dependent: :destroy end
neeraji2it/sharetribe
db/migrate/20130815075659_create_initial_payment_gateways.rb
<gh_stars>0 class CreateInitialPaymentGateways < ActiveRecord::Migration end
neeraji2it/sharetribe
db/migrate/20160428054249_add_listing_id_to_orders.rb
<filename>db/migrate/20160428054249_add_listing_id_to_orders.rb class AddListingIdToOrders < ActiveRecord::Migration def change add_column :orders, :listing_id, :integer end end
neeraji2it/sharetribe
db/migrate/20140222080916_remove_additional_transaction_types.rb
class RemoveAdditionalTransactionTypes < ActiveRecord::Migration end
neeraji2it/sharetribe
db/migrate/20160428052644_add_phone_no_to_orders.rb
class AddPhoneNoToOrders < ActiveRecord::Migration def change add_column :orders, :phone_no, :string end end
neeraji2it/sharetribe
db/migrate/20160419060328_add_details_to_orders.rb
<filename>db/migrate/20160419060328_add_details_to_orders.rb class AddDetailsToOrders < ActiveRecord::Migration def change add_column :orders, :card_expires_on, :date end end
neeraji2it/sharetribe
app/models/custom_field_option_selection.rb
# == Schema Information # # Table name: custom_field_option_selections # # id :integer not null, primary key # custom_field_value_id :integer # custom_field_option_id :integer # listing_id :integer # created_at :datetime # updated_at :datetime # # Indexes # # index_custom_field_option_selections_on_custom_field_option_id (custom_field_option_id) # index_custom_field_option_selections_on_custom_field_value_id (custom_field_value_id) # class CustomFieldOptionSelection < ActiveRecord::Base belongs_to :custom_field_value belongs_to :custom_field_option end
neeraji2it/sharetribe
spec/models/braintree_payment_gateway_spec.rb
# == Schema Information # # Table name: payment_gateways # # id :integer not null, primary key # community_id :integer # type :string(255) # braintree_environment :string(255) # braintree_merchant_id :string(255) # braintree_master_merchant_id :string(255) # braintree_public_key :string(255) # braintree_private_key :string(255) # braintree_client_side_encryption_key :text(65535) # checkout_environment :string(255) # checkout_user_id :string(255) # checkout_password :string(255) # created_at :datetime # updated_at :datetime # require 'spec_helper' describe BraintreePaymentGateway, type: :model do let(:gateway) { FactoryGirl.build(:braintree_payment_gateway) } describe "#configured?" do it "is not configured" do gateway.braintree_environment = "production" gateway.braintree_merchant_id = nil gateway.braintree_master_merchant_id = nil gateway.braintree_public_key = nil gateway.braintree_private_key = nil gateway.braintree_client_side_encryption_key = "xxx" expect(gateway.configured?).to be_falsey end it "is configured" do gateway.braintree_environment = "production" gateway.braintree_merchant_id = "merchant123" gateway.braintree_master_merchant_id = "mastermerchant_123" gateway.braintree_public_key = "<KEY>" gateway.braintree_private_key = "<KEY>" gateway.braintree_client_side_encryption_key = "xxx" expect(gateway.configured?).to be_truthy end end end
neeraji2it/sharetribe
db/migrate/20150902103231_remove_unused_listing_indecies.rb
class RemoveUnusedListingIndecies < ActiveRecord::Migration end
neeraji2it/sharetribe
spec/models/checkout_payment_spec.rb
<reponame>neeraji2it/sharetribe # == Schema Information # # Table name: payments # # id :integer not null, primary key # payer_id :string(255) # recipient_id :string(255) # organization_id :string(255) # transaction_id :integer # status :string(255) # created_at :datetime # updated_at :datetime # community_id :integer # payment_gateway_id :integer # sum_cents :integer # currency :string(255) # type :string(255) default("CheckoutPayment") # braintree_transaction_id :string(255) # # Indexes # # index_payments_on_payer_id (payer_id) # index_payments_on_transaction_id (transaction_id) # require 'spec_helper' describe CheckoutPayment, type: :model do let(:row1) { FactoryGirl.build(:payment_row, :title => "old bikes", :vat => 24, :sum_cents => 2000) } let(:row2) { FactoryGirl.build(:payment_row, :title => "fixing", :vat => 24, :sum_cents => 10000) } let(:row3) { FactoryGirl.build(:payment_row, :title => "transport", :vat => 24, :sum_cents => 300) } let(:payment) { FactoryGirl.build(:checkout_payment, rows: [row1, row2, row3]) } describe "#summary_string" do it "returns the row titles joined with comma" do expect(payment.summary_string).to eq("old bikes, fixing, transport") end end describe "#total_sum" do it "sums rows" do expect(payment.total_sum.cents).to eq((2000 + 10000 + 300) * 1.24) end end end
neeraji2it/sharetribe
db/migrate/20140811133606_initialize_transaction_type_urls.rb
<filename>db/migrate/20140811133606_initialize_transaction_type_urls.rb #require File.expand_path('../../migrate_helpers/logging_helpers', __FILE__) class InitializeTransactionTypeUrls < ActiveRecord::Migration end
neeraji2it/sharetribe
app/models/paypal_process_token.rb
# == Schema Information # # Table name: paypal_process_tokens # # id :integer not null, primary key # process_token :string(64) not null # community_id :integer not null # transaction_id :integer not null # op_completed :boolean default(FALSE), not null # op_name :string(64) not null # op_input :text(65535) # op_output :text(65535) # created_at :datetime # updated_at :datetime # # Indexes # # index_paypal_process_tokens_on_process_token (process_token) UNIQUE # index_paypal_process_tokens_on_transaction (transaction_id,community_id,op_name) UNIQUE # class PaypalProcessToken < ActiveRecord::Base attr_accessible( :process_token, :community_id, :paypal_token, :transaction_id, :op_completed, :op_name, :op_input, :op_output) validates_presence_of(:process_token, :community_id) end
neeraji2it/sharetribe
app/models/checkout_payment.rb
<gh_stars>0 # == Schema Information # # Table name: payments # # id :integer not null, primary key # payer_id :string(255) # recipient_id :string(255) # organization_id :string(255) # transaction_id :integer # status :string(255) # created_at :datetime # updated_at :datetime # community_id :integer # payment_gateway_id :integer # sum_cents :integer # currency :string(255) # type :string(255) default("CheckoutPayment") # braintree_transaction_id :string(255) # # Indexes # # index_payments_on_payer_id (payer_id) # index_payments_on_transaction_id (transaction_id) # class CheckoutPayment < Payment has_many :rows, :class_name => "PaymentRow", :foreign_key => "payment_id" def initialize_rows(community) if community.vat self.rows = [PaymentRow.new, PaymentRow.new, PaymentRow.new] else self.rows = [PaymentRow.new] end end def sum_exists? !rows.empty? end def summary_string rows.collect(&:title).join(", ") end # Total payment that will be charged from the payer's account def total_sum rows.collect(&:sum_with_vat).sum end # Build default payment sum by listing # Note: Consider removing this :( def default_sum(listing, vat=0) rows.build(title: listing.title, currency: listing.currency, sum: listing.price, vat: vat) end end
neeraji2it/sharetribe
db/migrate/20160420055332_add_listing_id_to_order.rb
class AddListingIdToOrder < ActiveRecord::Migration def change def self.up add_column :orders, :listing_id, :string end def self.down remove_column :orders, :listing_id, :string end end end
neeraji2it/sharetribe
db/migrate/20160419055239_create_order_transactions.rb
<filename>db/migrate/20160419055239_create_order_transactions.rb class CreateOrderTransactions < ActiveRecord::Migration def change create_table :order_transactions do |t| t.integer :order_id t.string :action t.integer :amount t.boolean :success t.string :authorization t.string :message t.text :params t.timestamps null: false end end end
neeraji2it/sharetribe
db/migrate/20140205121010_create_community_specific_categories.rb
#require File.expand_path('../../migrate_helpers/logging_helpers', __FILE__) class CreateCommunitySpecificCategories < ActiveRecord::Migration end
neeraji2it/sharetribe
app/models/order_transaction.rb
<reponame>neeraji2it/sharetribe # == Schema Information # # Table name: order_transactions # # id :integer not null, primary key # order_id :integer # action :string(255) # amount :integer # success :boolean # authorization :string(255) # message :string(255) # params :text(65535) # created_at :datetime not null # updated_at :datetime not null # class OrderTransaction < ActiveRecord::Base belongs_to :order serialize :params def response=(response) self.success = response.success? self.authorization = response.authorization self.message = response.message self.params = response.params rescue ActiveMerchant::ActiveMerchantError => e self.success = false self.authorization = nil self.message = e.message self.params = {} end end
neeraji2it/sharetribe
spec/models/custom_field_spec.rb
<reponame>neeraji2it/sharetribe<gh_stars>0 # == Schema Information # # Table name: custom_fields # # id :integer not null, primary key # type :string(255) # sort_priority :integer # search_filter :boolean default(FALSE), not null # created_at :datetime # updated_at :datetime # community_id :integer # required :boolean default(TRUE) # min :float(24) # max :float(24) # allow_decimals :boolean default(FALSE) # # Indexes # # index_custom_fields_on_community_id (community_id) # index_custom_fields_on_search_filter (search_filter) # require 'spec_helper' describe CustomField, type: :model do # These tests are testing FactoryGirl, not production code, thus, # these tests can be safely removed if needed describe "factory" do describe "build" do it "valid entity" do @custom_field = FactoryGirl.build(:custom_dropdown_field) expect(@custom_field).to be_valid end it "sets defaults" do @custom_field = FactoryGirl.build(:custom_dropdown_field) expect(@custom_field.names.length).to eq(1) expect(@custom_field.names.first.value).to eq("Test field") end describe "allows override defaults" do it "with empty value" do @custom_field = FactoryGirl.build(:custom_dropdown_field, names: []) expect(@custom_field).to be_valid # This is not possible. If you pass empty array, then factory girl uses defaults # @custom_field.names.length.should == 0 end it "with custom value" do @custom_field = FactoryGirl.build(:custom_dropdown_field, names: [FactoryGirl.build(:custom_field_name, value: "FactoryGirlTest")]) expect(@custom_field).to be_valid expect(@custom_field.names.length).to eq(1) expect(@custom_field.names.first.value).to eq("FactoryGirlTest") end end end describe "create" do it "valid entity" do @custom_field = FactoryGirl.create(:custom_dropdown_field) expect(@custom_field).to be_valid end it "doesn't override" do @custom_field = FactoryGirl.create(:custom_dropdown_field) expect(@custom_field).to be_valid end describe "allows override defaults" do it "with empty value" do @custom_field = FactoryGirl.create(:custom_dropdown_field, names: []) expect(@custom_field).to be_valid # This is not possible. If you pass empty array, then factory girl uses defaults # @custom_field.names.length.should == 0 end it "with custom value" do @custom_field = FactoryGirl.create(:custom_dropdown_field, names: [FactoryGirl.build(:custom_field_name, value: "FactoryGirlTest")]) expect(@custom_field).to be_valid expect(@custom_field.names.length).to eq(1) expect(@custom_field.names.first.value).to eq("FactoryGirlTest") end end end end describe "validations" do before(:each) do # Create valid CustomField entity @custom_field = FactoryGirl.create(:custom_dropdown_field) expect(@custom_field).to be_valid end it "should have min 1 name" do @custom_field.names = [] expect(@custom_field).not_to be_valid end it "should have min 1 category" do @custom_field.category_custom_fields = [] expect(@custom_field).not_to be_valid end end end
neeraji2it/sharetribe
spec/models/numeric_field_value_spec.rb
<gh_stars>0 # == Schema Information # # Table name: custom_field_values # # id :integer not null, primary key # custom_field_id :integer # listing_id :integer # text_value :text(65535) # numeric_value :float(24) # date_value :datetime # created_at :datetime # updated_at :datetime # type :string(255) # delta :boolean default(TRUE), not null # # Indexes # # index_custom_field_values_on_listing_id (listing_id) # index_custom_field_values_on_type (type) # require 'spec_helper' describe NumericFieldValue, type: :model do describe "validations" do it "should have text value" do @value = NumericFieldValue.new expect(@value).not_to be_valid # Has to be number @value.numeric_value = 0 expect(@value).to be_valid @value.numeric_value = "jee" expect(@value).not_to be_valid end end describe "search", :'no-transaction' => true do let!(:short_board) { FactoryGirl.create :listing, title: "Short board" } let!(:medium_board) { FactoryGirl.create :listing, title: "Medium board" } let!(:long_board) { FactoryGirl.create :listing, title: "Long board" } let!(:board_length) { FactoryGirl.create :custom_numeric_field, min: 0, max: 200 } let!(:length_value1) { FactoryGirl.create :custom_numeric_field_value, listing: short_board, question: board_length, numeric_value: 100 } let!(:length_value2) { FactoryGirl.create :custom_numeric_field_value, listing: medium_board, question: board_length, numeric_value: 160 } let!(:length_value3) { FactoryGirl.create :custom_numeric_field_value, listing: long_board, question: board_length, numeric_value: 200 } let!(:board_width) { FactoryGirl.create :custom_numeric_field, min: 0, max: 50 } let!(:width_value1) { FactoryGirl.create :custom_numeric_field_value, listing: short_board, question: board_width, numeric_value: 30 } let!(:width_value3) { FactoryGirl.create :custom_numeric_field_value, listing: long_board, question: board_width, numeric_value: 40 } before(:each) do ensure_sphinx_is_running_and_indexed end def test_search(length, width, expected_count) with_many = [] with_many << if length then { custom_field_id: board_length.id, numeric_value: length } end with_many << if width then { custom_field_id: board_width.id, numeric_value: width } end expect(NumericFieldValue.search_many(with_many.compact).count).to eq(expected_count) end it "searches by numeric field and value pairs" do test_search((0..50), (0..20), 0) # Neither matches test_search((0..150), (0..20), 0) # Length matches 1, width matches 0 test_search((0..150), (0..35), 1) # Length matches 1, width matches 1 test_search((0..180), nil, 2) # Length matches 2 test_search((0..220), nil, 3) # Length matches 3 test_search((0..220), (20..35), 1) # Length matches 3, width matches 1 test_search((0..220), (20..50), 2) # Length matches 3, width matches 2 end end end
neeraji2it/sharetribe
db/migrate/20140415092507_rename_dropdown_to_dropdown_field.rb
<gh_stars>0 class RenameDropdownToDropdownField < ActiveRecord::Migration end
neeraji2it/sharetribe
app/models/listing.rb
# encoding: utf-8 # == Schema Information # # Table name: listings # # id :integer not null, primary key # community_id :integer not null # author_id :string(255) # category_old :string(255) # title :string(255) # times_viewed :integer default(0) # language :string(255) # created_at :datetime # updates_email_at :datetime # updated_at :datetime # last_modified :datetime # sort_date :datetime # lastmodified :datetime # listing_type_old :string(255) # description :text(65535) # origin :string(255) # destination :string(255) # valid_until :datetime # delta :boolean default(TRUE), not null # open :boolean default(TRUE) # share_type_old :string(255) # privacy :string(255) default("private") # comments_count :integer default(0) # subcategory_old :string(255) # old_category_id :integer # category_id :integer # share_type_id :integer # listing_shape_id :integer # transaction_process_id :integer # shape_name_tr_key :string(255) # action_button_tr_key :string(255) # organization_id :integer # price_cents :integer # currency :string(255) # quantity :string(255) # unit_type :string(32) # quantity_selector :string(32) # unit_tr_key :string(64) # unit_selector_tr_key :string(64) # deleted :boolean default(FALSE) # require_shipping_address :boolean default(FALSE) # pickup_enabled :boolean default(FALSE) # shipping_price_cents :integer # shipping_price_additional_cents :integer # # Indexes # # homepage_query (community_id,open,sort_date,deleted) # homepage_query_valid_until (community_id,open,valid_until,sort_date,deleted) # index_listings_on_category_old (category_old) # index_listings_on_community_id (community_id) # index_listings_on_listing_shape_id (listing_shape_id) # index_listings_on_listing_type_old (listing_type_old) # index_listings_on_new_category_id (category_id) # index_listings_on_old_category_id (old_category_id) # index_listings_on_open (open) # index_listings_on_share_type_id (share_type_id) # index_listings_on_share_type_old (share_type_old) # person_listings (community_id,author_id) # updates_email_listings (community_id,open,updates_email_at) # class Listing < ActiveRecord::Base include ApplicationHelper include ActionView::Helpers::TranslationHelper include Rails.application.routes.url_helpers belongs_to :author, :class_name => "Person", :foreign_key => "author_id" has_many :listing_images, -> { where("error IS NULL") }, :dependent => :destroy has_many :conversations has_many :comments, :dependent => :destroy has_many :custom_field_values, :dependent => :destroy has_many :custom_dropdown_field_values, :class_name => "DropdownFieldValue" has_many :custom_checkbox_field_values, :class_name => "CheckboxFieldValue" has_one :location, :dependent => :destroy has_one :origin_loc, -> { where('location_type = ?', 'origin_loc') }, :class_name => "Location", :dependent => :destroy has_one :destination_loc, -> { where('location_type = ?', 'destination_loc') }, :class_name => "Location", :dependent => :destroy accepts_nested_attributes_for :origin_loc, :destination_loc has_and_belongs_to_many :followers, :class_name => "Person", :join_table => "listing_followers" belongs_to :category has_many :orders monetize :price_cents, :allow_nil => true, with_model_currency: :currency monetize :shipping_price_cents, allow_nil: true, with_model_currency: :currency monetize :shipping_price_additional_cents, allow_nil: true, with_model_currency: :currency before_validation :set_valid_until_time validates_presence_of :author_id validates_length_of :title, :in => 2..60, :allow_nil => false before_create :set_sort_date_to_now def set_sort_date_to_now self.sort_date ||= Time.now end before_create :set_updates_email_at_to_now def set_updates_email_at_to_now self.updates_email_at ||= Time.now end before_validation do # Normalize browser line-breaks. # Reason: Some browsers send line-break as \r\n which counts for 2 characters making the # 5000 character max length validation to fail. # This could be more general helper function, if this is needed in other textareas. self.description = description.gsub("\r\n","\n") if self.description end validates_length_of :description, :maximum => 5000, :allow_nil => true validates_presence_of :category validates_inclusion_of :valid_until, :allow_nil => :true, :in => DateTime.now..DateTime.now + 7.months validates_numericality_of :price_cents, :only_integer => true, :greater_than_or_equal_to => 0, :message => "price must be numeric", :allow_nil => true def self.currently_open(status="open") status = "open" if status.blank? case status when "all" where([]) when "open" where(["open = '1' AND (valid_until IS NULL OR valid_until > ?)", DateTime.now]) when "closed" where(["open = '0' OR (valid_until IS NOT NULL AND valid_until < ?)", DateTime.now]) end end def visible_to?(current_user, current_community) ListingVisibilityGuard.new(self, current_community, current_user).visible? end # sets the time to midnight def set_valid_until_time if valid_until self.valid_until = valid_until.utc + (23-valid_until.hour).hours + (59-valid_until.min).minutes + (59-valid_until.sec).seconds end end # Overrides the to_param method to implement clean URLs def to_param "#{id}-#{title.to_url}" end def self.columns super.reject { |c| c.name == "transaction_type_id" || c.name == "visibility"} end def self.find_by_category_and_subcategory(category) Listing.where(:category_id => category.own_and_subcategory_ids) end # Returns true if listing exists and valid_until is set def temporary? !new_record? && valid_until end def update_fields(params) update_attribute(:valid_until, nil) unless params[:valid_until] update_attributes(params) end def closed? !open? || (valid_until && valid_until < DateTime.now) end # Send notifications to the users following this listing # when the listing is updated (update=true) or a # new comment to the listing is created. def notify_followers(community, current_user, update) followers.each do |follower| unless follower.id == current_user.id if update MailCarrier.deliver_now(PersonMailer.new_update_to_followed_listing_notification(self, follower, community)) else MailCarrier.deliver_now(PersonMailer.new_comment_to_followed_listing_notification(comments.last, follower, community)) end end end end def image_by_id(id) listing_images.find_by_id(id) end def prev_and_next_image_ids_by_id(id) listing_image_ids = listing_images.collect(&:id) ArrayUtils.next_and_prev(listing_image_ids, id); end def has_image? !listing_images.empty? end def icon_name category.icon_name end # The price symbol based on this listing's price or community default, if no price set def price_symbol price ? price.symbol : MoneyRails.default_currency.symbol end def answer_for(custom_field) custom_field_values.find { |value| value.custom_field_id == custom_field.id } end def payment_required_at?(community) price && price > 0 && community.payments_in_use? end def unit_type Maybe(read_attribute(:unit_type)).to_sym.or_else(nil) end end
neeraji2it/sharetribe
app/models/custom_field_values/numeric_field_value.rb
# == Schema Information # # Table name: custom_field_values # # id :integer not null, primary key # custom_field_id :integer # listing_id :integer # text_value :text(65535) # numeric_value :float(24) # date_value :datetime # created_at :datetime # updated_at :datetime # type :string(255) # delta :boolean default(TRUE), not null # # Indexes # # index_custom_field_values_on_listing_id (listing_id) # index_custom_field_values_on_type (type) # class NumericFieldValue < CustomFieldValue attr_accessible :numeric_value validates_numericality_of :numeric_value def display_value question.allow_decimals ? numeric_value : numeric_value.to_i end # See self._search_many # This is just dummy wrapper to log the execution time def self.search_many(with_many, ids=[]) TimingService.log(0.5, "Searching with #{with_many.count} numeric fields took too long") { NumericFieldValue._search_many(with_many, ids) } end private # Recursive function that does multiple sphinx searches # # Give an array of filtering options and get back search results that # matches all the options # # Usage: # with_many = [{ # custom_field_id: board_length.id, # numeric_value: (0..50) # }, { # custom_field_id: board_width.id, # numeric_value: (0..20) # }] # # NumericFieldValue.search_many(with_many) => search result # def self._search_many(with_many, ids=[]) if with_many.length == 0 NumericFieldValue.search_with_listing_ids({}, ids) elsif (with_many.length == 1) NumericFieldValue.search_with_listing_ids(with_many.first, ids) else first_with, *rest_withs = *with_many # http://devblog.avdi.org/2010/01/31/first-and-rest-in-ruby/ new_ids = NumericFieldValue._search_many(rest_withs, ids).collect(&:listing_id) if new_ids.empty? # Stop searching, if nothing found new_ids else NumericFieldValue.search_with_listing_ids(first_with, new_ids) end end end def self.search_with_listing_ids(with, ids) NumericFieldValue.search(with: with.merge({listing_id: ids}), per_page: ListingIndexService::Search::SphinxAdapter::SPHINX_MAX_MATCHES) end end
neeraji2it/sharetribe
db/migrate/20140223202734_fix_price_quantity_placeholders.rb
<filename>db/migrate/20140223202734_fix_price_quantity_placeholders.rb class CommunityCategory < ActiveRecord::Base belongs_to :community belongs_to :category belongs_to :share_type end class ShareType < ActiveRecord::Base has_many :sub_share_types, :class_name => "ShareType", :foreign_key => "parent_id" # children is a more generic alias for sub share_types, used in classification.rb has_many :children, :class_name => "ShareType", :foreign_key => "parent_id" belongs_to :parent, :class_name => "ShareType" has_many :community_categories has_many :communities, :through => :community_categories has_many :listings has_many :translations, :class_name => "ShareTypeTranslation", :dependent => :destroy end class FixPriceQuantityPlaceholders < ActiveRecord::Migration end
neeraji2it/sharetribe
app/models/payment_row.rb
<gh_stars>0 # == Schema Information # # Table name: payment_rows # # id :integer not null, primary key # payment_id :integer # vat :integer # sum_cents :integer # currency :string(255) # created_at :datetime # updated_at :datetime # title :string(255) # # Indexes # # index_payment_rows_on_payment_id (payment_id) # class PaymentRow < ActiveRecord::Base include MathHelper attr_accessible :payment_id, :vat, :sum, :currency, :title belongs_to :payment monetize :sum_cents, with_model_currency: :currency def sum_with_vat sum_with_percentage(sum, vat) end # The price symbol based on this listing's price or community default, if no price set def sum_symbol sum ? sum.symbol : MoneyRails.default_currency.symbol end end
neeraji2it/sharetribe
db/migrate/20130328155825_add_payment_to_community_categories.rb
<reponame>neeraji2it/sharetribe<gh_stars>0 class AddPaymentToCommunityCategories < ActiveRecord::Migration end
neeraji2it/sharetribe
db/migrate/20090225073742_add_column_last_modified_to_listing.rb
<gh_stars>0 class AddColumnLastModifiedToListing < ActiveRecord::Migration def self.up add_column :listings, :lastmodified, :datetime end def self.down remove_column :listings, :lastmodified, :datetime end end
neeraji2it/sharetribe
spec/models/order_spec.rb
<reponame>neeraji2it/sharetribe # == Schema Information # # Table name: orders # # id :integer not null, primary key # firstname :string(255) # lastname :string(255) # email :string(255) # cardtype :string(255) # cardno :string(255) # username :string(255) # created_at :datetime not null # updated_at :datetime not null # express_token :string(255) # express_payer_id :string(255) # card_expires_on :date # phone_no :string(255) # listing_id :integer # require 'rails_helper' RSpec.describe Order, type: :model do pending "add some examples to (or delete) #{__FILE__}" end
neeraji2it/sharetribe
app/controllers/orders_controller.rb
class OrdersController < ApplicationController def index @listing = Listing.find(params[:listing_id]) @orders= Order.all end def express response = EXPRESS_GATEWAY.setup_purchase(current_cart.build_order.price_in_cents, :ip => request.remote_ip, :return_url => new_order_url, :cancel_return_url => products_url ) redirect_to EXPRESS_GATEWAY.redirect_url_for(response.token) end def new @listing = Listing.find(params[:listing_id]) @order = Order.new(:express_token => params[:token]) end def create @listing = Listing.find(params[:listing_id]) @order= Order.new(order_params.merge(:listing_id => @listing.id)) #@order.ip_address = request.remote_ip if @order.save && @order.purchase UserMailer.welcome_email(@order).deliver! render :action => "success" else render :action => 'new' end end def update @order= Order.find(params[:id]) if @order.update(order_params) redurect_to root_path else render"edit" end end def edit @order= Order.find(params[:id]) end def show @order= Order.find(params[:id]) end def destroy @order= Order.find(params[:id]) @order.destroy redirect_to root_path end def order_params params.require(:order).permit! end def purchase response = process_purchase transactions.create!(:action => "purchase", :amount => price_in_cents, :response => response) cart.update_attribute(:purchased_at, Time.now) if response.success? response.success? end def express_token=(token) write_attribute(:express_token, token) if new_record? && !token.blank? details = EXPRESS_GATEWAY.details_for(token) self.express_payer_id = details.payer_id self.firstname = details.params["firstname"] self.lastname = details.params["lastname"] end end private def process_purchase if express_token.blank? STANDARD_GATEWAY.purchase(price_in_cents, credit_card, standard_purchase_options) else EXPRESS_GATEWAY.purchase(price_in_cents, express_purchase_options) end end def standard_purchase_options { :ip => ip_address, :billing_address => { :name => "<NAME>", :address1 => "123 Main St.", :city => "New York", :state => "NY", :country => "US", :zip => "10001" } } end def express_purchase_options { :ip => ip_address, :token => express_token, :payer_id => express_payer_id } end def validate_card if express_token.blank? && !credit_card.valid? credit_card.errors.full_messages.each do |message| errors.add_to_base message end end end end
neeraji2it/sharetribe
db/migrate/20160419094945_add_person_id_to_orders.rb
<reponame>neeraji2it/sharetribe class AddPersonIdToOrders < ActiveRecord::Migration def change def self.up add_column :orders, :persons_id, :string end def self.down remove_column :orders, :persons_id, :string end end end
neeraji2it/sharetribe
db/migrate/20160418121807_create_orders.rb
class CreateOrders < ActiveRecord::Migration def change create_table :orders do |t| t.string :firstname t.string :lastname t.string :email t.string :cardtype t.string :cardno t.string :username t.timestamps null: false end end end
neeraji2it/sharetribe
db/migrate/20131112115308_migrate_organization_users.rb
<reponame>neeraji2it/sharetribe class MigrateOrganizationUsers < ActiveRecord::Migration end
neeraji2it/sharetribe
app/models/custom_fields/option_field.rb
<reponame>neeraji2it/sharetribe<gh_stars>0 # == Schema Information # # Table name: custom_fields # # id :integer not null, primary key # type :string(255) # sort_priority :integer # search_filter :boolean default(FALSE), not null # created_at :datetime # updated_at :datetime # community_id :integer # required :boolean default(TRUE) # min :float(24) # max :float(24) # allow_decimals :boolean default(FALSE) # # Indexes # # index_custom_fields_on_community_id (community_id) # index_custom_fields_on_search_filter (search_filter) # class OptionField < CustomField has_many :options, :class_name => "CustomFieldOption", :dependent => :destroy, :foreign_key => 'custom_field_id' # attributes structure: # # { # <option_id>: { # title_attributes: { # <locale>: <translation>, # ... # }, # sort_priority: <prio> # }, # ... # } # def option_attributes=(attributes) options_hash = options.includes(:titles).map { |option| { id: option.id, sort_priority: option.sort_priority, title_attributes: option.titles.map { |title| [title.locale, title.value] }.to_h } } attributes_hash = attributes.map { |opts| { id: str_to_integer(opts[:id]), sort_priority: opts[:sort_priority].to_i, title_attributes: opts[:title_attributes] } } diff = ArrayUtils.diff_by_key(options_hash, attributes_hash, :id) Maybe(diff.select { |d| d[:action] == :added }.map { |added| added[:value] }).each { |added| options.build(added) } Maybe(diff.select { |d| d[:action] == :removed }.map { |removed| removed[:value][:id] }).each { |removed_ids| options.where(id: removed_ids).destroy_all } diff.select { |d| d[:action] == :changed }.map { |added| added[:value] }.each { |changed| options.where(id: changed[:id]).first.update_attributes(changed) } end def str_to_integer(s) if s.nil? nil elsif !/\A\d+\z/.match(s) # not positive integer nil else s.to_i end end end
neeraji2it/sharetribe
db/migrate/20131114112955_migrate_difficult_organization_users.rb
<reponame>neeraji2it/sharetribe class MigrateDifficultOrganizationUsers < ActiveRecord::Migration end
neeraji2it/sharetribe
app/models/mercury/image.rb
# == Schema Information # # Table name: mercury_images # # id :integer not null, primary key # image_file_name :string(255) # image_content_type :string(255) # image_file_size :integer # image_updated_at :datetime # created_at :datetime # updated_at :datetime # class Mercury::Image < ActiveRecord::Base self.table_name = :mercury_images attr_accessible :image has_attached_file :image, :styles => { :medium => "300x300>", :thumb => "100x100>" }, :path => "images/mercury/:attachment/:id/:style/:filename", :url => "/system/:class/:attachment/:id/:style/:filename" validates_attachment_content_type :image, :content_type => ["image/jpeg", "image/png", "image/gif", "image/pjpeg", "image/x-png"] delegate :url, :to => :image def serializable_hash(options = nil) options ||= {} options[:methods] ||= [] options[:methods] << :url super(options) end end
neeraji2it/sharetribe
app/models/booking.rb
# == Schema Information # # Table name: bookings # # id :integer not null, primary key # transaction_id :integer # start_on :date # end_on :date # created_at :datetime # updated_at :datetime # # Indexes # # index_bookings_on_transaction_id (transaction_id) # class Booking < ActiveRecord::Base belongs_to :tx, class_name: "Transaction", foreign_key: "transaction_id" attr_accessible :transaction_id, :end_on, :start_on validates :start_on, :end_on, presence: true validates_with DateValidator, attribute: :end_on, compare_to: :start_on, restriction: :on_or_after ## TODO REMOVE THIS def duration (end_on - start_on).to_i + 1 end end
neeraji2it/sharetribe
db/migrate/20140611094703_change_type_to_listing_conversation.rb
<reponame>neeraji2it/sharetribe<gh_stars>0 class ChangeTypeToListingConversation < ActiveRecord::Migration end
neeraji2it/sharetribe
app/models/paypal_payment.rb
<filename>app/models/paypal_payment.rb # == Schema Information # # Table name: paypal_payments # # id :integer not null, primary key # community_id :integer not null # transaction_id :integer not null # payer_id :string(64) not null # receiver_id :string(64) not null # merchant_id :string(255) not null # order_id :string(64) # order_date :datetime # currency :string(8) not null # order_total_cents :integer # authorization_id :string(64) # authorization_date :datetime # authorization_expires_date :datetime # authorization_total_cents :integer # payment_id :string(64) # payment_date :datetime # payment_total_cents :integer # fee_total_cents :integer # payment_status :string(64) not null # pending_reason :string(64) # created_at :datetime # updated_at :datetime # commission_payment_id :string(64) # commission_payment_date :datetime # commission_status :string(64) default("not_charged"), not null # commission_pending_reason :string(64) # commission_total_cents :integer # commission_fee_total_cents :integer # # Indexes # # index_paypal_payments_on_authorization_id (authorization_id) UNIQUE # index_paypal_payments_on_community_id (community_id) # index_paypal_payments_on_order_id (order_id) UNIQUE # index_paypal_payments_on_transaction_id (transaction_id) UNIQUE # class PaypalPayment < ActiveRecord::Base attr_accessible( :community_id, :transaction_id, :payer_id, :receiver_id, :merchant_id, :order_id, :order_date, :currency, :order_total_cents, :authorization_id, :authorization_date, :authorization_expires_date, :authorization_total_cents, :payment_id, :payment_date, :payment_total_cents, :fee_total_cents, :payment_status, :pending_reason, :commission_payment_id, :commission_payment_date, :commission_total_cents, :commission_fee_total_cents, :commission_status, :commission_pending_reason) validates_presence_of( :community_id, :transaction_id, :payer_id, :receiver_id, :currency, :payment_status, :commission_status) monetize :order_total_cents, with_model_currency: :currency, allow_nil: true monetize :authorization_total_cents, with_model_currency: :currency, allow_nil: true monetize :payment_total_cents, with_model_currency: :currency, allow_nil: true monetize :fee_total_cents, with_model_currency: :currency, allow_nil: true monetize :commission_total_cents, with_model_currency: :currency, allow_nil: true monetize :commission_fee_total_cents, with_model_currency: :currency, allow_nil: true end
neeraji2it/sharetribe
spec/models/order_transaction_spec.rb
<reponame>neeraji2it/sharetribe # == Schema Information # # Table name: order_transactions # # id :integer not null, primary key # order_id :integer # action :string(255) # amount :integer # success :boolean # authorization :string(255) # message :string(255) # params :text(65535) # created_at :datetime not null # updated_at :datetime not null # require 'rails_helper' RSpec.describe OrderTransaction, type: :model do pending "add some examples to (or delete) #{__FILE__}" end
neeraji2it/sharetribe
app/helpers/api/people_helper.rb
module Api::PeopleHelper end
neeraji2it/sharetribe
spec/controllers/api/people_controller_spec.rb
require 'rails_helper' RSpec.describe Api::PeopleController, type: :controller do end
boostify/bic_validation
spec/bic_validation/bic_validator_spec.rb
require 'spec_helper' module BicValidation describe BicValidator do class Model include ActiveModel::Validations attr_accessor :bic validates :bic, bic: true def initialize(bic) @bic = bic end end it 'is valid' do model = Model.new 'DEUTDEFF' model.valid? expect(model.errors.count).to eq(0) end it 'is unknown' do model = Model.new 'DXUTDEFF' model.valid? expect(model.errors.count).to eq(1) end it 'is invalid' do model = Model.new 'DXUTDE' model.valid? expect(model.errors.count).to eq(1) end end end
boostify/bic_validation
lib/bic_validation/bic.rb
<reponame>boostify/bic_validation<filename>lib/bic_validation/bic.rb require 'active_support/core_ext/object/try' module BicValidation class Bic attr_accessor :code def initialize(code) @code = code.to_s.strip.upcase end def of_valid_length? [8, 11].include? @code.length end def of_valid_format? @code =~ format end def has_valid_country_code? country_codes.include? country end def has_valid_location_code? # WTF? http://de.wikipedia.org/wiki/ISO_9362 location[0] =~ /[^01]/ && location[1] =~ /[^O]/ end def known? !known_bics.include?(country.to_sym) || known_bics[country.to_sym].include?(@code.try(:gsub, /XXX$/, '')) end def valid? of_valid_length? && of_valid_format? && has_valid_country_code? && has_valid_location_code? end def invalid? !valid? end def bank match[1] end def country match[2] end def location match[3] end def branch match[4] end private def format /([A-Z]{4})([A-Z]{2})([0-9A-Z]{2})([0-9A-Z]{3})?/ end def match format.match(@code) end def known_bics { DE: bics(:de), AT: bics(:at), CH: bics(:ch) } end def bics(country) BankingData::Bank.where(locale: country).only(:bic) .map { |bic| bic.first.gsub(/XXX$/, '') } .reject(&:blank?) .uniq end def country_codes # http://www.iso.org/iso/country_codes/iso_3166_code_lists/country_\ # names_and_code_elements.htm YAML.load(File.read(File.dirname(__FILE__) + '/country_codes.yml')) end end end
boostify/bic_validation
lib/bic_validation.rb
<reponame>boostify/bic_validation require 'active_model' require 'banking_data' require 'bic_validation/bic' require 'bic_validation/bic_validator' require 'bic_validation/version' module BicValidation end ActiveModel::Validations.send(:include, BicValidation) I18n.load_path += Dir[File.expand_path(File.join(File.dirname(__FILE__), '../locales', '*.yml')).to_s]
boostify/bic_validation
lib/bic_validation/bic_validator.rb
module BicValidation class BicValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) bic = Bic.new(value) if bic.valid? unless bic.known? record.errors.add attribute, :unknown_bic end else record.errors.add attribute, :invalid end end end end
boostify/bic_validation
spec/bic_validation/bic_spec.rb
<filename>spec/bic_validation/bic_spec.rb require 'spec_helper' module BicValidation describe Bic do context 'with bogus data' do it 'survives nil data' do bic = Bic.new(nil) expect(bic).to be_invalid end it 'survives integer data' do bic = Bic.new(123) expect(bic).to be_invalid end it 'survives float data' do bic = Bic.new(1.23) expect(bic).to be_invalid end end context 'basic methods 11 digit' do before { @bic = Bic.new 'MARKDEF1850' } subject { @bic } describe '#valid?' do it { should be_valid } end describe '#known?' do it { should be_known } end describe '#bank' do its(:bank) { should eq('MARK') } end describe '#country' do its(:country) { should eq('DE') } end describe '#location' do its(:location) { should eq('F1') } end describe '#branch' do its(:branch) { should eq('850') } end end context 'basic methods 8 digit' do before { @bic = Bic.new 'DEUTDEBB' } subject { @bic } describe '#valid?' do it { should be_valid } end describe '#known?' do it { should be_known } end describe '#bank' do its(:bank) { should eq('DEUT') } end describe '#country' do its(:country) { should eq('DE') } end describe '#location' do its(:location) { should eq('BB') } end describe '#branch' do its(:branch) { should be_nil } end end ['DEUTDEBB', 'CRESCHZZ10S', 'UBSWCHZH86N', 'OEKOATWWXXX', 'OEKOATWW', 'BTRLRO22'].each do |swift| describe 'validity checks' do it "validates #{swift}" do bic = Bic.new(swift) expect(bic).to be_valid expect(bic).to be_known end end end end end
hsupu/kaiyuanshe
src/_plugins/DirGenerator.rb
# frozen_string_literal: true module Jekyll module Generators class DirectoryVariables < Generator def generate(site) baseurl = site.config['baseurl'] site.config['assets'] = { "favicon_dir" => "#{baseurl}/assets/favicon", "js_dir" => "#{baseurl}/assets/js", "css_dir" => "#{baseurl}/assets/css", "images_dir" => "#{baseurl}/static/images", } end end end end
bricooke/active_merchant
lib/active_merchant/billing/bank_account.rb
module ActiveMerchant #:nodoc: module Billing #:nodoc: # == Description # This bank account object can be used as a stand alone object. It acts just like an ActiveRecord object # but doesn't support the .save method as its not backed by a database. # # For testing purposes, use the 'bogus' bank account type. This account skips the vast majority of # validations. This allows you to focus on your core concerns until you're ready to be more concerned # with the details of particular creditcards or your gateway. # # == Testing With BankAccount # Often when testing we don't care about the particulars of a given card type. When using the 'test' # mode in your Gateway, there are six different valid bank account numbers: 1, 2, 3, 'success', 'fail', # and 'error'. # #-- # For details, see BankAccountMethods#valid_account? #++ # # == Example Usage # ba = BankAccount.new( # :first_name => 'Steve', # :last_name => 'Smith', # :type => 'checking', # :bank_name => 'Bank of America', # :echeck_type => 'ccd', # :routing_number => '123456789', # :account_number => '111000025' # # ba.valid? # => true # ba.display_number # => XXXX5678 # class BankAccount include Validateable ## Attributes # Essential attributes for a valid, non-bogus bank account attr_accessor :account_number, :routing_number, :first_name, :last_name, :type, :echeck_type # Additional optional attributes attr_accessor :bank_name def name? first_name? && last_name? end def first_name? !@first_name.blank? end def last_name? !@last_name.blank? end def name "#{@first_name} #{@last_name}" end def account_number? !account_number.blank? end def routing_number? !routing_number.blank? end # Show the account number, with all but last 4 numbers replaced with "X". (XXXX4338) def display_number # ('X' * (account_number.to_s.length - last_digits.size)) + last_digits # account_number.to_s[0..last_digits.size].to_s.size + # last_digits.to_s end def last_digits account_number.to_s.length <= 4 ? account_number.to_s : account_number.to_s.slice(-4..-1) end def validate validate_essential_attributes # Bogus account is pretty much for testing purposes. Lets just skip these extra tests if its used return if type == 'bogus' validate_account_type validate_routing_number validate_echeck_type end private def before_validate #:nodoc: self.account_number = account_number.to_s.gsub(/[^\d]/, "") self.routing_number = routing_number.to_s.gsub(/[^\d]/, "") self.type.downcase! if type.respond_to?(:downcase) self.type = "checking" if type.blank? end def validate_essential_attributes #:nodoc: errors.add :first_name, "cannot be empty" if @first_name.blank? errors.add :last_name, "cannot be empty" if @last_name.blank? errors.add :account_number, "cannot be empty" if @account_number.blank? end def validate_account_type #:nodoc: errors.add :type, "is invalid" unless ["checking","bogus","savings","business_checking"].include?(type) end def validate_routing_number #:nodoc: errors.add :routing_number, "cannot be empty" if @routing_number.blank? errors.add :routing_number, "should be 9 digits" if @routing_number.to_s.length != 9 errors.add :routing_number, "is invalid" unless valid_routing_number? end def validate_echeck_type #:nodoc: errors.add :echeck_type, "is invalid" unless echeck_type.nil? || ['ccd','ppd'].include?(echeck_type) end # Routing numbers may be validated by calculating a checksum and dividing it by 10. The # formula is: # (3(d1 + d4 + d7) + 7(d2 + d5 + d8) + 1(d3 + d6 + d9))mod 10 = 0 # See http://en.wikipedia.org/wiki/Routing_transit_number#Internal_checksums def valid_routing_number? d = routing_number.to_s.split('').map(&:to_i).select { |d| (0..9).include?(d) } case d.size when 9 then checksum = ((3 * (d[0] + d[3] + d[6])) + (7 * (d[1] + d[4] + d[7])) + (d[2] + d[5] + d[8])) % 10 case checksum when 0 then true else false end else false end end end end end
bricooke/active_merchant
test/unit/bank_acccount_test.rb
<gh_stars>1-10 require File.dirname(__FILE__) + '/../test_helper' class BankAccountTest < Test::Unit::TestCase def setup @checking = bank_account(:account_number => '123456', :routing_number => '111000025', :type => 'checking') @savings = bank_account(:account_number => '123456', :routing_number => '111000025', :type => 'savings') end def test_constructor_should_properly_assign_values b = bank_account assert_equal "11223344", b.account_number assert_equal "111000025", b.routing_number assert_equal "<NAME>", b.name assert_equal "checking", b.type assert_valid b end def test_new_bank_account_should_not_be_valid b = BankAccount.new assert_not_valid b assert_false b.errors.empty? end def test_should_be_a_valid_checking_account assert_valid @checking assert @checking.errors.empty? end def test_should_be_a_valid_savings_account assert_valid @savings assert @savings.errors.empty? end def test_accounts_with_empty_names_should_not_be_valid @checking.first_name = '' @checking.last_name = '' assert_not_valid @checking assert_false @checking.errors.empty? end def test_should_be_able_to_access_errors_indifferently @checking.first_name = '' assert_not_valid @checking assert @checking.errors.on(:first_name) assert @checking.errors.on("first_name") end def test_should_be_able_to_liberate_a_bogus_account b = bank_account(:routing_number => '', :type => 'bogus') assert_valid b b.type = 'checking' assert_not_valid b end def test_should_be_able_to_identify_invalid_routing_numbers @checking.routing_number = nil assert_not_valid @checking @checking.routing_number = "1234567ff" assert_not_valid @checking assert_false @checking.errors.on(:type) assert @checking.errors.on(:routing_number) @checking.routing_number = "1" assert_not_valid @checking assert_false @checking.errors.on(:type) assert @checking.errors.on(:routing_number) @checking.routing_number = "1234567890111" assert_not_valid @checking assert_false @checking.errors.on(:type) assert @checking.errors.on(:routing_number) @checking.routing_number = "abcdefghi" assert_not_valid @checking assert_false @checking.errors.on(:type) assert @checking.errors.on(:routing_number) end def test_should_be_a_valid_routing_number @checking.routing_number = "111000025" assert_valid @checking end def test_should_not_be_valid_with_invalid_type b = bank_account(:type => 'invalid') assert_not_valid b end def test_should_display_number assert_equal 'XXXXXXXXXXXX1234', BankAccount.new(:account_number => '1111222233331234').display_number assert_equal 'XXXXXXXXXXX1234', BankAccount.new(:account_number => '111222233331234').display_number assert_equal 'XXXXXXXXXX1234', BankAccount.new(:account_number => '11122233331234').display_number assert_equal '', BankAccount.new(:account_number => nil).display_number assert_equal '123', BankAccount.new(:account_number => '123').display_number assert_equal 'X2345', BankAccount.new(:account_number => '12345').display_number assert_equal '1234', BankAccount.new(:account_number => '1234').display_number end def test_should_return_last_four_digits_of_card_number b = BankAccount.new(:account_number => "4779139500118580") assert_equal "8580", b.last_digits end def test_bogus_last_digits b = BankAccount.new(:account_number => "1") assert_equal "1", b.last_digits end def test_should_be_true_when_bank_account_has_a_first_name c = BankAccount.new assert_false c.first_name? c = BankAccount.new(:first_name => 'James') assert c.first_name? end def test_should_be_true_when_bank_account_has_a_last_name c = BankAccount.new assert_false c.last_name? c = BankAccount.new(:last_name => 'Herdman') assert c.last_name? end def test_should_test_for_a_full_name c = BankAccount.new assert_false c.name? c = BankAccount.new(:first_name => 'James', :last_name => 'Herdman') assert c.name? end # The following is a regression for a bug that raised an exception when # a new credit card was validated def test_validate_new_card bank_account = BankAccount.new assert_nothing_raised do bank_account.validate end end def test_validating_bogus_card bank_account = bank_account(:account_number => '1', :type => nil) assert bank_account.valid? end def test_strip_non_digit_characters b = bank_account(:account_number => '4242-4242 %%%%%%4242......4242', :routing_number => '11100 %% WOO BLAH @#$@ 0025') assert b.valid? assert_equal "4242424242424242", b.account_number assert_equal "111000025", b.routing_number end def test_before_validate_handles_blank_number b = bank_account(:account_number => nil) assert !b.valid? assert_equal "", b.account_number end end
ChrisCrewdson/googlio
lib/mustachio/factories.rb
<reponame>ChrisCrewdson/googlio Magickly.add_convert_factory :mustachify do |c| c.convert_args do |eye_num_param, convert| identity = convert.pre_identify width = identity[:width] height = identity[:height] # resize to smaller than 900px, because Face.com downsizes the image to this anyway # TODO move resize inside of Mustachio.face_data faces = convert.image.thumb('900x900>').face_data_as_px(width, height) commands = ['-alpha Background -background Transparent'] faces.each do |face| eye_num = case eye_num_param when true 0 when 'true' 0 when 'rand' rand(Mustachio.eyes.size) else eye_num_param.to_i end eye = Mustachio.eyes[eye_num] face['eye_center'] ||= { 'x' => ((face['eye_left']['x'] + face['eye_right']['x']) / 2.0), 'y' => ((face['eye_left']['y'] + face['eye_right']['y']) / 2.0) } # perform transform such that the mustache is the height # of the upper lip, and the bottom-center of the stache # is mapped to the center of the mouth rotation = Math.atan(( face['eye_right']['y'] - face['eye_left']['y'] ).to_f / ( face['eye_right']['x'] - face['eye_left']['x'] ).to_f ) / Math::PI * 180.0 desired_height = Math.sqrt( ( face['nose']['x'] - face['eye_center']['x'] ).to_f**2 + ( face['nose']['y'] - face['eye_center']['y'] ).to_f**2 ) eye_intersect = eye['height'] - eye['eye_overlap'] scale = desired_height / eye_intersect srt_params = [ [ eye['width'] / 2.0, eye_intersect - eye['vert_offset'] ].map{|e| e.to_i }.join(','), # bottom-center of stache scale, # scale rotation, # rotate [ face['eye_center']['x'], face['eye_center']['y'] ].map{|e| e.to_i }.join(',') # middle of mouth ] srt_params_str = srt_params.join(' ') commands << "\\( #{eye['file_path']} +distort SRT '#{srt_params_str}' \\)" end commands << "-flatten" commands.join(' ') end end
hyc286716320/HYCBaseViewController
HYCBaseViewController.podspec
Pod::Spec.new do |s| s.name = 'HYCBaseViewController' s.version = '1.0' s.license = { :type => "MIT", :file => "LICENSE" } s.summary = 'UIViewController父类,能快速实现UINav的一些设置,非常实用' s.homepage = 'https://github.com/hyc286716320/HYCBaseViewController' s.author = {'HuYunchao' => 'hyc286716320'} s.source = { :git => 'https://github.com/hyc286716320/HYCBaseViewController.git', :tag =>s.version} s.platform = :ios s.source_files = 'HYCBaseViewController/HYCBaseViewController' s.requires_arc = true #s.dependency 'ReactiveCocoa','~> 2.5' s.dependency "Masonry" s.dependency 'FDFullscreenPopGesture' end
february29/FchKit
FchKit.podspec
<gh_stars>0 # # Be sure to run `pod lib lint FchKit.podspec' to ensure this is a # valid spec before submitting. # # Any lines starting with a # are optional, but their use is encouraged # To learn more about a Podspec see https://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.name = 'FchKit' s.version = '0.2.4' s.summary = 'A short description of FchKit.' # This description is used to generate tags and improve search results. # * Think: What does it do? Why did you write it? What is the focus? # * Try to keep it short, snappy and to the point. # * Write the description between the DESC delimiters below. # * Finally, don't worry about the indent, CocoaPods strips it! s.description = <<-DESC TODO: Add long description of the pod here. DESC s.homepage = 'https://github.com/february29/FchKit' # s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2' s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { 'february29' => '<EMAIL>' } s.source = { :git => 'https://github.com/february29/FchKit.git', :tag => s.version.to_s } # s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>' s.ios.deployment_target = '8.0' s.subspec 'FchSwiftKit' do |ss| # ss.source_files = 'FchKit/Classes/FchSwiftKit/**/*' ss.subspec 'Adapter' do |sss| sss.source_files = 'FchKit/Classes/FchSwiftKit/Adapter/**/*' end ss.subspec 'BBaseClass' do |sss| sss.source_files = 'FchKit/Classes/FchSwiftKit/BBaseClass/**/*' end ss.subspec 'BTools' do |sss| sss.source_files = 'FchKit/Classes/FchSwiftKit/BTools/**/*' end ss.subspec 'CommonViews' do |sss| sss.source_files = 'FchKit/Classes/FchSwiftKit/CommonViews/**/*' end ss.subspec 'BNetWorking' do |sss| sss.source_files = 'FchKit/Classes/FchSwiftKit/BNetWorking/BAlamofireManager.swift' sss.dependency 'Alamofire' # sss.dependency 'HandyJSON' #sss.dependency 'RxSwift' end ss.dependency 'SnapKit' ss.dependency 'BAlert' end s.subspec 'FchOCKit' do |ss| #ss.source_files = 'FchKit/Classes/FchOCKit/*.{h,m}' ss.subspec 'BNetWorking' do |sss| sss.source_files = 'FchKit/Classes/FchOCKit/BNetWorking/**/*' sss.dependency 'AFNetworking' end ss.subspec 'BToolKit' do |sss| sss.source_files = 'FchKit/Classes/FchOCKit/BToolKit/**/*' end ss.subspec 'BaseClass' do |sss| sss.source_files = 'FchKit/Classes/FchOCKit/BaseClass/**/*' end # ss.subspec 'BHUD' do |sss| # sss.source_files = 'FchKit/Classes/FchOCKit/BHUD/**/*' # end # ss.subspec 'CommenLib' do |sss| # sss.source_files = 'FchKit/Classes/FchOCKit/CommenLib/**/*' # sss.dependency 'SDWebImage' #end ss.subspec 'CommenViews' do |sss| sss.source_files = 'FchKit/Classes/FchOCKit/CommenViews/**/*' # sss.dependency 'SDWebImage' end ss.dependency 'Masonry' # ss.dependency 'BHUD' ss.dependency 'BlocksKit' end s.swift_version = '4.2' # s.source_files = 'FchKit/Classes/**/*' # s.resource_bundles = { # 'FchKit' => ['FchKit/Assets/*.png'] # } # s.public_header_files = 'Pod/Classes/**/*.h' # s.frameworks = 'UIKit', 'MapKit' end
nedgar/rollout-ui
spec/rollout/ui/web_spec.rb
require 'spec_helper' ENV['APP_ENV'] = 'test' RSpec.describe 'Web UIp' do include Rack::Test::Methods def app Rollout::UI::Web end it "renders index html" do get '/' expect(last_response.body.include?('Rollout UI')) expect(last_response.status == 200) end it "renders index json" do ROLLOUT.activate(:fake_test_feature_for_rollout_ui_webspec) header 'Accept', 'application/json' get '/' expect(last_response.status == 200) expect(last_response.headers['Content-Type'] == 'application/json') response = JSON.parse(last_response.body) expected_response = { "data"=>{}, "groups"=>[], "name"=>"fake_test_feature_for_rollout_ui_webspec", "percentage"=>100.0 } expect(response).to(include(expected_response)) ROLLOUT.delete(:fake_test_feature_for_rollout_ui_webspec) end it "renders index json filtered by user and group" do ROLLOUT.deactivate(:fake_test_feature_for_rollout_ui_webspec) ROLLOUT.activate_user(:fake_test_feature_for_rollout_ui_webspec, 'fake_user') ROLLOUT.activate_group(:fake_test_feature_for_rollout_ui_webspec, :fake_group) header 'Accept', 'application/json' get '/?user=different_user' expect(last_response.status == 200) expect(last_response.headers['Content-Type'] == 'application/json') response = JSON.parse(last_response.body) expect(response == []) expected_feature = { "data" => {}, "groups" => ["fake_group"], "name" => "fake_test_feature_for_rollout_ui_webspec", "percentage" => 0.0 } header 'Accept', 'application/json' get '/?user=fake_user' expect(last_response.status == 200) expect(last_response.headers['Content-Type'] == 'application/json') response = JSON.parse(last_response.body) expect(response).to(include(expected_feature)) header 'Accept', 'application/json' get '/?group=fake_group' expect(last_response.status == 200) expect(last_response.headers['Content-Type'] == 'application/json') response = JSON.parse(last_response.body) expect(response).to(include(expected_feature)) ROLLOUT.deactivate_user(:fake_test_feature_for_rollout_ui_webspec, 'fake_user') ROLLOUT.deactivate_group(:fake_test_feature_for_rollout_ui_webspec, :fake_group) ROLLOUT.delete(:fake_test_feature_for_rollout_ui_webspec) end it "renders show html" do get '/features/test' expect(last_response.body.include?('Rollout UI')) expect(last_response.body.include?('test')) expect(last_response.status == 200) end it "renders show json" do ROLLOUT.activate(:fake_test_feature_for_rollout_ui_webspec) header 'Accept', 'application/json' get '/features/fake_test_feature_for_rollout_ui_webspec' expect(last_response.status == 200) expect(last_response.headers['Content-Type'] == 'application/json') response = JSON.parse(last_response.body) expected_response = { "data"=>{}, "groups"=>[], "name"=>"fake_test_feature_for_rollout_ui_webspec", "percentage"=>100.0 } expect(expected_response == response) ROLLOUT.delete(:fake_test_feature_for_rollout_ui_webspec) end end
badshark/http-cage
test/spec/httpcage_spec.rb
require_relative '_init' require 'net/http' require 'uri' describe 'HTTPCage' do before do HTTPCage.timeout(connection: 1, request: 2, ssl: 3) end it 'overrides Net::HTTP timeouts' do client = Net::HTTP.new('google.com') client.open_timeout.must_equal 1 client.read_timeout.must_equal 2 client.ssl_timeout.must_equal 3 end it 'can be overridden by another cage' do HTTPCage.timeout(connection: 10, request: 20, ssl: 30) client = Net::HTTP.new('google.com') client.open_timeout.must_equal 10 client.read_timeout.must_equal 20 client.ssl_timeout.must_equal 30 end it 'will not timeout on a routable address' do client = Net::HTTP.new('httpbin.org') get = Net::HTTP::Get.new('/') client.request(get).code.must_equal "200" end it 'will timeout during connection on a non-routable address' do client = Net::HTTP.new('10.255.255.1') get = Net::HTTP::Get.new('/') proc { client.request(get).body }.must_raise Net::OpenTimeout end it 'will timeout during request on a slow responding address' do uri = URI.parse('https://httpbin.org/delay/10') client = Net::HTTP.new(uri.host, uri.port) get = Net::HTTP::Get.new(uri.request_uri) proc { client.request(get).body }.must_raise Net::ReadTimeout end end
ritxi/shrine-reform
test/reform_test.rb
<filename>test/reform_test.rb<gh_stars>0 require "test_helper" require "reform" require "reform/rails" describe Shrine::Plugins::Reform do before do @uploader = uploader do plugin :activerecord plugin :reform end ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:") ActiveRecord::Base.connection.create_table(:records) do |t| t.text :attachment_data end ActiveRecord::Base.connection.create_table(:nested_records) do |t| t.integer :record_id t.text :attachment_data end record_class = Object.const_set("Record", Class.new(ActiveRecord::Base)) record_class.table_name = :records record_class.include @uploader.class::Attachment.new(:attachment) record_class.has_many :nested_records nested_class = Object.const_set("NestedRecord", Class.new(ActiveRecord::Base)) nested_class.table_name = :nested_records nested_class.include @uploader.class::Attachment.new(:attachment) nested_class.belongs_to :record nested_form_class = Class.new(Reform::Form) nested_form_class.include @uploader.class::Attachment.new(:attachment) form_class = Class.new(Reform::Form) form_class.include @uploader.class::Attachment.new(:attachment) form_class.collection :nested_records, populate_if_empty: NestedRecord, form: nested_form_class @record = record_class.new @form = form_class.new(@record) end after do ActiveRecord::Base.remove_connection Object.send(:remove_const, "Record") Object.send(:remove_const, "NestedRecord") end it "prepopulates attachment" do @record.attachment = StringIO.new @form.prepopulate! assert_kind_of Shrine::UploadedFile, @form.attachment end it "doesn't error when there is nothing to prepopulate" do @form.prepopulate! end it "populates attachment" do @form.validate(attachment: StringIO.new) assert_kind_of Shrine::UploadedFile, @form.attachment @form.validate(nested_records: [{attachment: StringIO.new}]) assert_kind_of Shrine::UploadedFile, @form.nested_records[0].attachment end it "merges attachment validations" do @record.attachment_attacher.class.validate { errors << "Error" } @form.validate(attachment: StringIO.new) assert_equal ["Error"], @form.errors[:attachment] @form.validate(nested_records: [{attachment: StringIO.new}]) assert_equal ["Error"], @form.errors["nested_records.attachment"] end it "syncs attachment" do @form.validate(attachment: StringIO.new) @form.sync assert_kind_of Shrine::UploadedFile, @record.attachment @form.validate(nested_records: [{attachment: StringIO.new}]) @form.sync assert_kind_of Shrine::UploadedFile, @record.nested_records[0].attachment end it "doesn't sync when attachment wasn't set" do @record.attachment = StringIO.new @form.sync assert_kind_of Shrine::UploadedFile, @record.attachment end it "syncs attachment removal" do @record.attachment = StringIO.new @form.prepopulate! @form.validate(attachment: nil) @form.sync assert_nil @record.attachment end it "doesn't sync attachment that hasn't changed" do @record.attachment_data = @record.attachment_attacher.cache!(StringIO.new).to_json @form.prepopulate! @form.sync refute @record.attachment_attacher.attached? end it "doesn't sync when model doesn't have attachment module" do @record.instance_eval { undef attachment= } @form.attachment = StringIO.new @form.sync assert_nil @record.attachment_data end it "detects remote_url plugin" do refute_respond_to @form, :attachment_remote_url @uploader.class.plugin :remote_url, max_size: nil @form.class.prepend @uploader.class[:attachment] assert_respond_to @form, :attachment_remote_url end it "detects data_uri plugin" do refute_respond_to @form, :attachment_data_uri @uploader.class.plugin :data_uri @form.class.prepend @uploader.class[:attachment] assert_respond_to @form, :attachment_data_uri end it "detects remote_attachment plugin" do refute_respond_to @form, :remove_attachment @uploader.class.plugin :remove_attachment @form.class.prepend @uploader.class[:attachment] assert_respond_to @form, :remove_attachment end it "detects cached_attachment_data plugin" do refute_respond_to @form, :cached_attachment_data @uploader.class.plugin :cached_attachment_data @form.class.prepend @uploader.class[:attachment] assert_respond_to @form, :cached_attachment_data end it "doesn't define any Reform methods on non-Reform objects" do refute_respond_to @record, :prepopulate! refute_respond_to @record, :sync end end
ritxi/shrine-reform
test/test_helper.rb
<filename>test/test_helper.rb ENV["RAILS_ENV"] = "test" require "bundler/setup" require_relative "../test/dummy/config/environment" require "minitest/autorun" require "minitest/pride" require "shrine" require "shrine/storage/memory" require "shrine/plugins/reform" require "stringio" class Minitest::Spec def uploader(storage_key = :store, &block) uploader_class = Class.new(Shrine) uploader_class.storages[:cache] = Shrine::Storage::Memory.new uploader_class.storages[:store] = Shrine::Storage::Memory.new uploader_class.class_eval(&block) if block uploader_class.new(storage_key) end def fakeio StringIO.new end end
mjacobus/landing-careers-challenge
lib/api_client.rb
class ApiClient def get(uri:, params: {}) raise "Cannot connect to the internet" end end
mjacobus/landing-careers-challenge
lib/user_service.rb
class UserService def initialize(api_client:) @client = api_client end def find_by_id(id) data = @client.get('/users/1') User.new(data) end end
mjacobus/landing-careers-challenge
spec/user_service_spec.rb
<filename>spec/user_service_spec.rb require "spec_helper" RSpec.describe UserService do let(:client) { double(ApiClient) } subject { UserService.new(api_client: client) } describe '#find_user_by_id' do before do allow(client).to receive(:get).with('/users/1').and_return({ id: 1, name: '<NAME>', }) end it 'returns a valid user' do user = subject.find_by_id(1) expect(user).to be_a(User) expect(user.name).to eq('<NAME>') end end end
mjacobus/landing-careers-challenge
lib/user.rb
<gh_stars>0 class User attr_reader :id, :name def initialize(attributes = {}) @id = attributes[:id] @name = attributes[:name] end end
YaoJuan/by_mega
lib/mega_loto/drawing.rb
module MegaLoto class Drawing def draw 6.times.map { single_row } end private def single_row rand(0...60) end end end
YaoJuan/by_mega
lib/mega_loto.rb
<gh_stars>0 require "mega_loto/version" require 'mega_loto/drawing' begin require "pry" rescue LoadError end module MegaLoto end
dryack/clij
clij.rb
<gh_stars>0 #! /usr/local/opt/ruby193/bin/ruby # *sigh* require 'jenkins_api_client' require 'yaml' require 'net/https' require 'cron2english' require 'gli' require './Logd' require './clij-lib' include GLI::App program_desc 'Manage Jenkins via command line' subcommand_option_handling :normal sort_help :manually config_file '.clij.rc' flag [:u, :username], :arg_name => 'user', :desc => 'Jenkins server username' flag [:p, :password], :arg_name => 'password', :mask => true, :desc => 'Jenkins server password' flag :i, :arg_name => 'ip_address', :desc => 'Jenkins server IP address', :must_match => /\d+\.\d+\.\d+\.\d+/ flag [:n, :port], :arg_name => 'port_number', :desc => 'Port number used by Jenkins', :default_value => '8080', :must_match => /\d+/ flag [:l, :logname], :arg_name => 'log-file-name', :desc => 'Log all output to log-file-name' flag [:j, :path], :arg_name => 'path_to_jenkins', :desc => 'Path to Jenkins', :default_value => '/' flag [:g, :log_level], :arg_name => 'level', :desc => 'Jenkins API Log Levels to view/log', :default_value => 1, :must_match => { "debug" => 0, "info" => 1, "warn" => 2, "error" => 3, "fatal" => 4} flag :header, :arg_name => 'clij message header', :desc => 'Header used by clij to identify its management of a field in Jenkins' switch :ssl, :desc => 'Use SSL to connect to Jenkins' switch :o, :desc => 'Send output to STDOUT', :default_value => true, :negatable => true def check_args?(args,help_msg="job_name is required") $log.debug(args) if args.nil? || args.empty? help_now!(help_msg) $log.debug("check_args? returns FALSE") return false else $log.debug("check_args? returns TRUE") return true end end desc 'Work with jobs' long_desc 'View information on or manipulate settings of jobs' command :job do |c| c.desc 'List/find jobs managed by Jenkins' c.command :list do |list| list.desc 'List all jobs on the server' list.command :all do |all| all.action do |global_options, options, args| @waldo = Waldo.new @waldo.job_list_all end end # list all list.arg_name 'job_name' list.desc 'List all jobs containing job_name' list.action do |global_options, options, args| if check_args?(args, "job_name is required, or try 'clij job list all'") @waldo = Waldo.new(args[0]) @waldo.job_search_name end end # list <search> end # list c.desc 'View details about or manipulate job polling' c.command :poll do |poll| poll.arg_name 'job_name' poll.desc 'Examine the polling status of jobs' poll.command :status do |status| status.desc 'Print whether polling is enabled for each job on the server -- WARNING: This is likely to fail on overburdened servers.' status.command :all do |all| all.action do |global_options, options, args| @waldo = Waldo.new @waldo.all_poll_status end end # poll status all status.arg_name 'job_name' status.desc 'Show (detailed) infomations regarding the polling used by a job' status.switch [:d,:detailed], :desc => 'Provide detailed information on the polling', :default_value => false status.switch [:r,:parse], :desc => 'Attempt to provide english description of chrontab format', :defualt_value => false status.action do |global_options, options, args| if check_args?(args, "job_name is required, or try 'clij job status all'") unless options[:detailed] request_type = 'basic' $log.debug("request_type 'basic'") else request_type = 'detailed' $log.debug("request_type 'detailed'") end @waldo = Waldo.new(args[0]) @waldo.job_poll_status(request_type) if options[:parse] @waldo.parse_trigger_spec end end end # poll status job_name end # poll status poll.desc "Revert the most recent clij-caused change to a job's polling data" poll.command :revert do |revert| revert.action do |global_options, options, args| if check_args?(args) @waldo = Waldo.new(args[0]) @waldo.revert_trigger_spec end end end # poll revert poll.arg_name 'job_name "spec"' poll.desc 'Write a spec and/or comments to a job. Old information is backed up automatically.' poll.command :write do |write| write.action do |global_options, options, args| if check_args?(args) @waldo = Waldo.new(args.shift) spec = args.join(" ") @waldo.write_trigger_spec(spec) end end end # poll write end # poll c.desc "Toggle the 'Discard Old Builds' checkbox and/or manipulate its settings" c.command :discard do |discard| discard.arg_name '[all|job_name]' discard.command :off do |off| off.desc 'Shut off the discarding of the old build' off.command :all do |all| all.action do |global_options, options, args| if global_options[:log_level] == "debug" $log.debug("NOTE: 'clij job discard off all' will not be run while in debug mode.") $log.debug("skipped method: all_discard_off()") else @waldo = Waldo.new #@waldo.all_discard_off end end end # discard off all off.action do |global_options, options, args| if check_args?(args, "job_name is required or try 'clij job discard off all'") @waldo = Waldo.new(args[0]) @waldo.job_discard_off end end # discard off end discard.arg_name '[all|job_name] [<days_to_keep>] [<max_num_to_keep> <artifacts_days> <artifacts_max_num_builds>]' discard.command :on do |on| on.desc 'Activate the discarding of old builds' on.command :all do |all| all.action do |global_options, options, args| if global_option[:log_level] == "debug" $log.debug("NOTE: 'clij job discard on all' will not be run while in debug mode.") else @waldo = Waldo.new #@waldo.all_discard_on(...) end end end # discard on all on.action do |global_options, options, args| if check_args?(args, "job_name is required") @waldo = Waldo.new(args.shift) unless args.empty? daystokeep = args.shift unless args.empty? numtokeep = args.shift unless args.empty? artifactdaystokeep = args.shift unless args.empty? artifactnumtokeep = args.shift @waldo.job_discard_on(daystokeep, numtokeep, artifactdaystokeep, artifactnumtokeep) else @waldo.job_discard_on(daystokeep, numtokeep, artifactdaystokeep) end else @waldo.job_discard_on(daystokeep, numtokeep) end else @waldo.job_discard_on(daystokeep) end else @waldo.job_discard_on end end end # discard on <job> end # job discard on end # job discard c.desc 'View details about or manipulate build retention' c.command :build do |build| build.command :status do |status| status.arg_name 'job_name' status.desc 'Show details regarding the build retention of a job' status.action do |global_options, options, args| if check_args?(args) @waldo = Waldo.new(args[0]) @waldo.job_build_status end end end # build status end # build end # job # Spits out configuration information # in the format expected by Jenskin::Client def get_client_opts(global) client_opts = { :server_ip => global[:i], :server_port => global[:port], :jenkins_path => global[:path], :username => global[:username], :password => global[:password], :ssl => global[:ssl], :log_level => global[:log_level], :msg_header => global[:header] } return client_opts end # Needed because we've got two logger # objects, only one of which is under # our direct control. meh def get_logging_level(global) case global[:log_level] when 0 return Logger::DEBUG when 1 return Logger::INFO when 2 return Logger::WARN when 3 return Logger::ERROR when 4 return Logger::FATAL else return Logger::INFO end end pre do |global,command,options,arg| $log = Logger.new(STDOUT) client_opts = get_client_opts(global) unless client_opts.has_key?(:msg_header) && client_opts[:msg_header].nil? == false $CLIJ_MSG_HEADER = "### WARNING: This field is being managed, in part, by clij.\n### Manual changes are discouraged.\n" else $CLIJ_MSG_HEADER = client_opts[:msg_header] end $log.level = get_logging_level(global) $log.info("LOG LEVEL SET TO: #{$log.level}") p global[:log_level] if global[:logname] $log.attach(global[:logname]) client_opts[:log_location] = global[:logname] end $log.debug("Global options; #{global}") $log.debug("Options: #{options}") $log.debug("Client options: #{client_opts}") $client = JenkinsApi::Client.new(client_opts) end exit run(ARGV)
dryack/clij
Logd.rb
require 'logger' class Logger # Creates or opens a secondary log file. def attach(name) @logdev.attach(name) end # Closes a secondary log file. def detach(name) @logdev.detach(name) end class LogDevice # :nodoc: attr_reader :devs def attach(log) @devs ||= {} @devs[log] = open_logfile(log) end def detach(log) @devs ||= {} @devs[log].close @devs.delete(log) end alias_method :old_write, :write def write(message) old_write(message) @devs ||= {} @devs.each do |log, dev| dev.write(message) end end end end
dryack/clij
clij-lib.rb
require 'jenkins_api_client' require 'net/https' require 'cron2english' require './Logd' class Waldo def new(*job) initialize(job) end def initialize(*job) @DUMP_FILE = ".clij-list.tmp" @HOMEDIR = File.expand_path("~") $log.debug("\nEntering Waldo::initialize") unless job.empty? || job.nil? @job = job.pop $log.debug("Waldo instance initialized, job = #{@job}") else $log.debug("Waldo instance initialized") end end def all_poll_status $log.debug("\nEntering Waldo::all_poll_status") # normal run? unless dump_file? $log.debug("No dump file found; starting normally") job_list = $client.job.list_all # did we find a dump_file from an interrupted run? else job_list = load_dump_file end # start the job run job_list.each do |job| if job == "BASE_JAVA_JOB" || job == "FAMC" job_list.delete("BASE_JAVA_JOB") job_list.delete("FAMC") next else $log.info("#{@job} => #{$client.job.get_config(job).include?('<spec>')}") end job_list.shift $log.debug("#{job_list[0]}") end rescue Interrupt recoverable_action(job_list) end def all_poll_off # will actually set all to poll once per month, spread out across the month # unless overridden? maybe? # probably just call job_poll_change() with a hardcoded approach? $log.debug("\nEntering Waldo::all_poll_off") end def all_poll_revert # possibly needed counterpart to above? $log.debug("\nEntering Waldo::all_poll_revert") end def job_poll_status(request_type='basic') # will check the poll status for a given job: # basic: yes or no # detailed: returns "no" or "yes, <details> <if there are old details that can be # reverted to>" $log.debug("\nEntering Waldo::job_poll_status") doc = config_obtain $log.debug("config.xml parsed") if request_type == 'detailed' if doc.to_s.include?('<spec>') $log.info(clean_txt(doc.xpath("//spec"))) else $log.info "No polling found for job #{@job}" end elsif request_type.nil? || request_type == 'basic' $log.info(doc.to_s.include?('<spec>')) else $log.error "Unsupported option in job_poll_status" end end def job_build_status(job) # will check to see if 'Discard Old Builds' is checked # and if so, the details of the setting(s) $log.debug("\nEntering Waldo::job_build_status") doc = config_obtain $log.debug("config.xml parsed") if discard_checkbox?(doc) $log.info("days to keep: #{clean_txt(doc.xpath("//daysToKeep"))}") $log.info("num to keep: #{clean_txt(doc.xpath("//numToKeep"))}") $log.info("artifacts days to keep: #{clean_txt(doc.xpath("//artifactDaysToKeep"))}") $log.info("artifacts num to keep: #{clean_txt(doc.xpath("//artifactNumToKeep"))}") else $log.info "'Discard Old Builds' is not checked for #{@job} (or individual settings remain unset)" end end def write_trigger_spec(spec) # will write a spec to <hudson.triggers.SCMTrigger><spec> $log.debug("\nEntering Waldo::write_trigger_spec") doc = config_obtain $log.debug("config.xml parsed") if doc.search('spec').empty? puts "#{@job} doesn't have polling set in its configuration." else polling = doc.at_css "spec" $log.debug("polling = doc.at_css 'spec'") unless polling.content.include?("#{$CLIJ_MSG_HEADER}") # $log.debug("No header found") polling.content = "#{$CLIJ_MSG_HEADER}\n" + "#{spec}\n\n" + polling.content.split("\n").map {|y| "### " + y}.join("\n") else $log.debug("Header found") split_polling = parsing_spec(polling.content) if split_polling["backedup"].empty? # no backed up spec exists - replace header, add new spec, rebuild # comments and currently active code polling.content.clear polling.content = "#{$CLIJ_MSG_HEADER}\n" + "#{spec}\n\n" + split_polling["comments"].map {|y| "### " + y}.join("\n") + "\n" + split_polling["activecode"].map {|y| "### " +y}.join("\n") else # existing backed up spec in place - we do NOT push down here; # replace header, add new spec, replace CURRENT backed up code polling.content.clear polling.content = "#{$CLIJ_MSG_HEADER}\n" + "#{spec}\n\n" + split_polling["backedup"].join("\n") end end $log.debug("Attempting to POST update to job") $client.job.update(@job, doc.to_xml) end end def revert_trigger_spec # will revert to the saved poll settings found in the comments, and then delete # the programmed comments; returns an error if nothing is found # error if none found $log.debug("\nEntering Waldo::job_poll_revert") doc = config_obtain $log.debug("config.xml parsed") if doc.search('spec').empty? puts "#{@job} is not set up for polling" elsif doc.search('spec').grep(/#{$CLIJ_MSG_HEADER}/).empty? puts "#{@job} is not being managed by clij, or has already been reverted" else polling = doc.at_css "spec" split_polling = parsing_spec(polling.content) if split_polling["backedup"].empty? $log.info("No back up trigger spec found!") return 0 else polling.content.clear polling.content = "#{$CLIJ_MSG_HEADER}\n" + split_polling["backedup"].map {|y| y.gsub("### ", '').join("\n")} end $client.job.update(@job, doc.to_xml) end end def parse_trigger_spec # will make sense of <hudson.triggers.SCMTrigger><spec> $log.debug("\nEntering Waldo::parse_trigger_spec") doc = config_obtain doc = doc.search('spec').to_s.gsub!(/<\/?spec>/,'') unless doc.to_s.empty? puts "\n#{@job} polling schedule:" doc.each_line.to_a.each do |x| unless x.start_with?('#') puts x puts Cron2English.parse(x.gsub(/H/,'*').gsub(/,0-/,',00-')) puts "" end end else puts "#{@job} has no polling schedule!" end end def job_discard_off $log.debug("\nEntering Waldo::job_discard_off") doc = config_obtain $log.debug("config.xml parsed") if doc.search('logRotator').empty? job_discard_create(-1, -1, -1, -1) else job_discard_change(-1, -1, -1, -1) end end def job_discard_on(daystokeep, numtokeep, adaystokeep, anumtokeep) $log.debug("\nentering Waldo::job_discard_on") doc = config_obtain $log.debug("config.xml parsed") if doc.search('logRotator').empty? job_discard_create(daystokeep, numtokeep, adaystokeep, anumtokeep) else job_discard_change(daystokeep, numtokeep, adaystokeep, anumtokeep) end end def job_discard_change(daystokeep, numtokeep, artifactdaystokeep, artifactnumtokeep) $log.debug("\nentering Waldo::job_discard_change") doc = config_obtain $log.debug("config.xml parsed") days = doc.at_css "daysToKeep" num = doc.at_css "numToKeep" artday = doc.at_css "artifactDaysToKeep" artnum = doc.at_css "artifactNumToKeep" days.content = daystokeep num.content = numtokeep artday.content = artifactdaystokeep artnum.content = artifactnumtokeep $client.job.update(@job, doc.to_xml) end def all_discard_off() $log.debug("\nEntering Waldo::all_discard_off") $client.job.list_all.each { |job| job_discard_off(job) } end def job_discard_create(daystokeep="-1", numtokeep="5", artifactdaystokeep="-1", artifactnumtokeep="-1") $log.debug("\nEntering Waldo::job_discard_create") doc = config_obtain root = doc.root $log.debug("config obtained") node = Nokogiri::XML::Node.new('logRotator', root) $log.debug("node logRotator created") node_days_to_keep = Nokogiri::XML::Node.new('daysToKeep', root) $log.debug("node logRotator child daysToKeep created") node_num_to_keep = Nokogiri::XML::Node.new('numToKeep', root) $log.debug("node logRotator child numToKeep created") a_node_days_to_keep = Nokogiri::XML::Node.new('artifactDaysToKeep', root) $log.debug("node logRotator child artifactDaysToKeep created") a_node_num_to_keep = Nokogiri::XML::Node.new('artifactNumToKeep', root) $log.debug("node logRotator child artifactNumToKeep created") node['class'] = 'hudson.tasks.LogRotator' $log.debug("node keys written") node_days_to_keep.content = daystokeep node_num_to_keep.content = numtokeep a_node_days_to_keep.content = artifactdaystokeep a _node_num_to_keep.content = artifactnumtokeep $log.debug("child nodes created and populated") node.add_child(node_days_to_keep) node.add_child(node_num_to_keep) node.add_child(a_node_days_to_keep) node.add_child(a_node_num_to_keep) node.parent = root $client.job.update(@job, doc.to_xml) end def all_discard_on(daystokeep = "-1", numtokeep = "-1", artifactdaystokeep = "-1", artifactnumtokeep = "-1") $log.debug("\nEntering Waldo::all_discard_all") $client.job.list_all.each { |job| job_discard_on(daystokeep, numtokeep, artifactdaystokeep, artifactnumtokeep) } end def job_list_all # obtain a list of every job on the jenkins server $log.debug("\nEntering Waldo::job_list_all") $log.info($client.job.list_all) end def job_search_name # use regex to match partial_name and output to user $log.debug("\nEntering Waldo::job_search_name") to_filter = @job filtered_list = $client.job.list("#{to_filter}") if filtered_list.nil? || filtered_list == [] $log.info "Nothing found matching '#{@job}'" else $log.info(filtered_list) end rescue Timeout::Error => e puts "#{e} waiting on job.list(#{to_filter})" retry end ########################################################################## # private members past this point ########################################################################## private def config_obtain $log.debug("\nentering Waldo::config_obtain") Nokogiri::XML.parse($client.job.get_config(@job.to_s)) end def clean_txt(text) $log.debug("\nentering Waldo::clean_txt") text.to_s.gsub!(/<\/?[[:alpha:]]+>/,'') end def discard_checkbox?(doc) $log.debug("\nentering Waldo::discard_checkbox") if doc.to_s.include?('logRotator') && (( doc.xpath("//daysToKeep").inner_text.to_i > 0) || (doc.xpath("//numToKeep").inner_text.to_i > 0) || (doc.xpath("//artifactDaysToKeep").inner_text.to_i > 0) || (doc.xpath("//artifactNumToKeep").inner_text.to_i > 0)) return true else return false end end def parsing_spec(contents) # will take the current contents of <spec> and break it down into # "active code", "comments", and "backed up" # it will then return a hash of arrays of arrays: activecode =>, # comments =>, backedup => # # useful for dealing with edge cases, etc - allows rebuilding of a polling # spec by individual components split_contents = { "activecode" => [], "comments" => [], "backedup" => [] } contents.gsub!("#{$CLIJ_MSG_HEADER}\n", '') contents.split("\n").map do |line| if line.start_with?("### ") split_contents["backedup"] << line elsif line.start_with?("#") split_contents["comments"] << line else split_contents["activecode"] << line end end return split_contents end def recoverable_action(job_list) $log.debug("\nEntering Waldo::recoverable_action") file = File.open("#{@HOMEDIR}/#{@DUMP_FILE}", "w") $log.debug(file) save_data = Marshal.dump(job_list, file) $log.info("Remaining jobs dumped. Re-run command line to continue from where you left off.") end def load_dump_file # loads a found dump file and returns its contents # to the caller $log.debug("\nEntering Waldo::load_dump_file") $log.debug("Using dump file to restart job") file = File.open("#{@HOMEDIR}/#{@DUMP_FILE}", "r") list_of_jobs = Marshal.load(file) $log.debug("Deleting dump file...") File.delete("#{@HOMEDIR}/#{@DUMP_FILE}") return list_of_jobs end def dump_file? $log.debug("\nEntering Waldo::dump_file?") if File.file?("#{@HOMEDIR}/#{@DUMP_FILE}") return true else return false end end end # class Waldo
markus/googlecharts
lib/gchart/aliases.rb
class Gchart alias_method :background=, :bg= alias_method :chart_bg=, :graph_bg= alias_method :chart_color=, :graph_bg= alias_method :chart_background=, :graph_bg= alias_method :bar_color=, :bar_colors= alias_method :line_colors=, :bar_colors= alias_method :line_color=, :bar_colors= alias_method :slice_colors=, :bar_colors= alias_method :horizontal?, :horizontal alias_method :grouped?, :grouped alias_method :curved?, :curved end
markus/googlecharts
lib/gchart/version.rb
module GchartInfo #:nodoc: VERSION = "1.6.7" end