repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
ipublic/marketplace
|
spec/factories/determinations_ui_write_off_eligibility_determinations.rb
|
<filename>spec/factories/determinations_ui_write_off_eligibility_determinations.rb<gh_stars>0
FactoryBot.define do
factory :determinations_ui_write_off_eligibility_determination, class: 'Determinations::UiWriteOffEligibilityDetermination' do
end
end
|
ipublic/marketplace
|
spec/factories/wages_wages.rb
|
<gh_stars>0
FactoryBot.define do
factory :wages_wage, class: 'Wages::Wage' do
association :person_party
state_qtr_ui_total_wages { 40_125.32 }
state_qtr_ui_excess_wages { 5_125.11 }
state_qtr_ui_taxable_wages { state_qtr_ui_total_wages - state_qtr_ui_excess_wages }
end
end
|
ipublic/marketplace
|
spec/factories/quanta_time_periods.rb
|
<gh_stars>0
FactoryBot.define do
factory :quanta_time_period, class: 'Quanta::TimePeriod' do
end
end
|
ipublic/marketplace
|
spec/factories/determinations_individual_ui_liability_determinations.rb
|
FactoryBot.define do
factory :determinations_individual_ui_liability_determination, class: 'Determinations::IndividualUiLiabilityDetermination' do
end
end
|
ipublic/marketplace
|
app/models/parties/party_relationship_kind.rb
|
<gh_stars>0
module Parties
class PartyRelationshipKind
include Mongoid::Document
include Mongoid::Timestamps
field :key, type: Symbol
field :title, type: String
field :description, type: String
# List of PartyRoleKind roles that can be played between the Party pair
has_and_belongs_to_many :party_role_kinds,
class_name: 'Parties::PartyRoleKind'
# Optional business rules for validating a relationship instance
has_one :eligibility_policy,
class_name: 'EligibilityPolicies::EligibilityPolicy'
# embeds_many :comments, as: :commentable
index({ key: 1}, { unique: true })
validates_presence_of :key, :title
validates_uniqueness_of :key
validate :party_role_kind_pairing
before_validation :assign_key_and_title
private
def assign_key_and_title
write_attribute(:key, text_to_symbol(title)) if key.blank? && title.present?
write_attribute(:title, symbol_to_text(key)) if title.blank? && key.present?
end
def text_to_symbol(text)
text.to_s.parameterize.underscore.to_sym
end
def symbol_to_text(symbol)
symbol.to_s.titleize
end
# Logic to validate subject_party_role_kind => object_party_role_kind pairing
def party_role_kind_pairing
errors.add(:party_role_kinds, "must provide a specific role pair") unless party_role_kinds.size == 2
end
end
end
|
ipublic/marketplace
|
spec/factories/parties_naics_classifications.rb
|
<reponame>ipublic/marketplace
FactoryBot.define do
factory :parties_naics_classification, class: 'Parties::NaicsClassification' do
end
end
|
ipublic/marketplace
|
app/models/sagas/activities/activity.rb
|
<reponame>ipublic/marketplace
class Sagas::Activities::Activity
def do_work(work_item)
# logfile: activity title
# perform activity work
# logfile: activity success
# return value
end
def compensate(item, routing_slip)
item.result
# logfile: canceled instance
end
def work_item_queue_address
Uri.new("sb://activity_actions")
end
def uri_compensation_queue_address
Uri.new("sb://activity_cancel_actions")
end
end
|
ipublic/marketplace
|
spec/factories/quanta_cycles.rb
|
FactoryBot.define do
factory :quanta_cycle, class: 'Quanta::Cycle' do
end
end
|
ipublic/marketplace
|
app/models/roles/role_factory.rb
|
<filename>app/models/roles/role_factory.rb
module Roles
class RoleFactory
attr_accessor :party_role
def self.call(party, party_role_kind_key)
build(party, args).party_role
end
# look up party_role_kind
# validate role isn't already active for this party
def initialize(party, party_role_kind_key)
@party = party
@party_role_kind_key = party_role_kind_key
@party_role_kind = nil
@party_role = nil
find_party_role_kind
build_party_role
end
def find_party_role_kind
@party_role_kind = Parties::PartyRoleKind.find_by(key: @party_role_kind_key)
end
def build_party_role
if @party.active_party_roles_by_key(@party_role_kind_key).size == 0
@party_role = @party.party_roles.build(party_role_kind: @party_role_kind)
else
# Error condition, party already has this active role
@party_role = nil
end
end
def party_role
@party_role
end
end
end
|
ipublic/marketplace
|
spec/factories/financial_accounts_group_insurance_financial_accounts.rb
|
<gh_stars>0
FactoryBot.define do
factory :financial_accounts_group_insurance_financial_account, class: 'FinancialAccounts::GroupInsuranceFinancialAccount' do
end
end
|
ipublic/marketplace
|
app/models/fees/administrative_fee.rb
|
<reponame>ipublic/marketplace
class Fees::AdministrativeFee
include Mongoid::Document
end
|
ipublic/marketplace
|
app/models/determinations/individual_health_insurance_eligibility_determination.rb
|
class Determinations::IndividualHealthInsuranceEligibilityDetermination
include Mongoid::Document
end
|
ipublic/marketplace
|
spec/factories/roles_relationship_role_factories.rb
|
FactoryBot.define do
factory :roles_relationship_role_factory, class: 'Roles::RelationshipRoleFactory' do
end
end
|
ipublic/marketplace
|
spec/models/employers/employer_form_spec.rb
|
require 'rails_helper'
RSpec.describe Employers::EmployerForm, dbclean: true do
describe Employers::EmployerForm do
describe "##for_create" do
let(:contact_info) do
{ :first_name => 'Silky',
:last_name => 'Johnston',
:dob => '09/22/1981',
:email => '<EMAIL>',
:area_code => '202',
:number => '222-2222' }
end
let(:employer_info) do
{ :legal_name => "<NAME>",
:dba => '0234232',
:fein => '123456789',
:kind => 'C Corpation' }
#:sic_code, String
end
let(:address_info) do
{ :kind => 'primary',
:address_1 => '202 2nd St',
:address_2 => '',
:city => 'Washington',
:state => 'DC',
:zip => '20002',
:area_code => '202',
:number => '222-2222',
:extension => '' }
end
before do
Parties::PartyRoleKind.create!(key: :employee, title: 'Employee')
Parties::PartyRoleKind.create!(key: :employer, title: 'Employer')
Parties::PartyRelationshipKind.create!(key: :employment, title: 'Employment',
party_role_kinds: [
Parties::PartyRoleKind.find_by!(key: :employee),
Parties::PartyRoleKind.find_by!(key: :employer)
]
)
end
subject do
Employers::EmployerForm.for_create(contact_info: contact_info, employer_info: employer_info, address_info: address_info)
end
it 'creates a new employer party' do
expect(subject).to be_a(Employers::EmployerForm)
end
it 'can be saved and creates a new Party' do
expect { subject.save }.to change { Parties::Party.all.count }.by(1)
end
it 'can be saved and creates a new Organization' do
expect { subject.save }.to change { Parties::OrganizationParty.all.count }.by(1)
end
it 'can be saved and creates a new Person' do
expect { subject.save }.to change { Parties::PersonParty.all.count }.by(1)
end
end
end
end
|
ipublic/marketplace
|
app/models/timespans/timespan.rb
|
module Timespans
YEAR_MAXIMUM = 2099
YEAR_MINIMUM = 1980
class Timespan
include Mongoid::Document
include Mongoid::Timestamps
field :title, type: String
field :begin_on, type: Date
field :end_on, type: Date
field :type, type: String
has_many :wage_reports,
class_name: 'Wages::WageReport'
has_many :determinations,
class_name: 'Determinations::Determination'
# validates_presence_of :begin_on, :end_on
validate :ascending_dates
index({ title: 1}, {unique: true})
# scope :find_on, ->(date){ where(:begin_on.lte => date, :end_on.gte => date).to_a unless date.blank?; binding.pry }
# scope :find_on, ->(date){ where(:begin_on.lte => date, :end_on.gte => date) unless date.blank? }
scope :find_on, ->(date){ where(:begin_on.lte => date, :end_on.gte => date) unless date.blank? }
scope :find_title, ->(compare_title){ where(:title => compare_title) unless compare_title.blank? }
# after_validation :initialize_timespan
after_initialize :initialize_timespan
def predecessor
return nil unless begin_date.present?
preceding_timespans = self.find_on(begin_date - 1.day).entries
preceding_timespans.size == 1 ? preceding_timespans.first : nil
end
def self.current_timespan
where(:begin_on.lte => Time.now, :end_on.gte => Time.now).select{|s|s._type=="Timespans::QuarterYearTimespan"}.first
end
def self.current_quarters
where(:begin_on.gte => (Date.today - 1.years - 5.months), :end_on.lte => Date.today).select{|s|s._type=="Timespans::QuarterYearTimespan"}
end
def self.all_quarters
where('quarter' =>{'$in' => [1,2,3,4]}).flatten.uniq.sort{|a,b| b.begin_on - a.begin_on}
end
def kind
_type.to_s.demodulize.underscore.to_sym
end
def between?(compare_date)
range_present? && (compare_date.between?(begin_on, end_on)) ? true : false
end
def to_range
begin_on..end_on if range_present?
end
alias_method :min, :begin_on
alias_method :max, :end_on
alias_method :contains?, :between?
private
def range_present?
begin_on.present? && end_on.present?
end
def ascending_dates
return unless range_present?
errors.add(:begin_on, "must be earlier than End on #{end_on}") unless (begin_on <= end_on)
end
private
def initialize_timespan
end
end
end
|
ipublic/marketplace
|
app/controllers/tpas_controller.rb
|
<reponame>ipublic/marketplace<filename>app/controllers/tpas_controller.rb<gh_stars>0
class TpasController < ApplicationController
layout 'two_column'
before_action :authenticate_user!
def index
end
def get_tpas
@tpas = []
Parties::Party.each do |party|
if party.present?
kind = party.party_roles.first
if kind.present?
if kind.party_role_kind.key = :tpa
@tpas << party
end
end
end
end
render json: { data: @tpas }
end
end
|
ipublic/marketplace
|
app/models/quanta/timespan.rb
|
<filename>app/models/quanta/timespan.rb
# frozen_string_literal: true
module Quanta
# Length of time for which something lasts
class Timespan
include Mongoid::Document
include Mongoid::Timestamps
embeds_one :duration
has_many :sub_timespans
end
end
|
ipublic/marketplace
|
spec/models/parties/organization_party_spec.rb
|
require 'rails_helper'
module Parties
RSpec.describe OrganizationParty, type: :model, dbclean: :after_each do
it { is_expected.to have_many(:wage_reports)}
it { is_expected.to embed_many(:naics_classifications)}
let(:legal_name) { "<NAME>, Inc" }
let(:fein) { "065872626" }
let(:entity_kind) { :s_corporation }
let(:entity_id) { 234567 }
let(:is_foreign_entity) { false }
let(:wage_reports) { FactoryBot.build(:wages_wage_report) }
let(:determinations) { FactoryBot.build(:determinations_determination) }
let(:naics_classifications) { FactoryBot.build(:parties_naics_classification) }
let(:party_ledger) { FactoryBot.build(:financial_accounts_party_ledger) }
let(:party_ledger_account_balance) { FactoryBot.build(:financial_accounts_party_ledger_account_balance) }
let(:params) do
{
legal_name: legal_name,
fein: fein,
entity_id: entity_id,
entity_kind: entity_kind,
is_foreign_entity: is_foreign_entity,
# office_locations: [valid_office_location_attributes]
}
end
describe "A new model instance" do
context "with no arguments" do
subject { described_class.new }
it "should not be valid" do
subject.validate
expect(subject).to_not be_valid
end
end
context "with no legal_name" do
subject { described_class.new(params.except(:legal_name)) }
it "should not be valid" do
subject.validate
expect(subject).to_not be_valid
expect(subject.errors[:legal_name].first).to match(/can't be blank/)
end
end
context "with no fein" do
subject { described_class.new(params.except(:fein)) }
it "should not be valid" do
subject.validate
expect(subject).to_not be_valid
expect(subject.errors[:fein].first).to match(/can't be blank/)
end
end
context "with invalid fein" do
let(:bad_fein) {"123123"}
let(:invalid_params) {params.deep_merge({fein: bad_fein})}
let(:fein_error_message) {"#{bad_fein} is not a valid FEIN"}
subject {described_class.new(invalid_params) }
it "should not be valid" do
subject.validate
expect(subject).to_not be_valid
expect(subject.errors[:fein]).to eq [fein_error_message]
end
end
# context "with no office_locations" do
# let(:params) {params.except(:office_locations)}
# it "should fail validation" do
# expect(Organization.create(**params).errors[:office_locations].any?).to be_truthy
# end
# end
context "with all required arguments" do
subject {described_class.new(params) }
it "should be valid" do
subject.validate
expect(subject).to be_valid
end
context "and it is saved" do
it "should save" do
expect(subject.save).to eq true
end
context "it should be findable" do
before { subject.save! }
it "should return the instance" do
expect(described_class.find(subject.id.to_s)).to eq subject
end
end
end
end
end
end
end
|
ipublic/marketplace
|
app/models/determinations/ui_write_off_eligibility_determination.rb
|
class Determinations::UiWriteOffEligibilityDetermination
include Mongoid::Document
end
|
ipublic/marketplace
|
spec/factories/wages_wage_report_services.rb
|
<filename>spec/factories/wages_wage_report_services.rb
FactoryBot.define do
factory :wages_wage_report_service, class: 'Wages::WageReportService' do
end
end
|
ipublic/marketplace
|
app/models/parties/party_role.rb
|
# A Person or Organization may play different roles on the system. A Role may be declarative, stating a fact
# about the subject, for example: :employer, :s_corporation. Roles may include a relationship, which includes
# a specific role pair that references two object instances, for example: an :employment relationship that
# associates a person who has an :employee role with an organization that has an :employer role.
#
# Roles may be used for different purposes, including:
# * defining authorization/access priviledges
# * storing role-related information about a object
module Parties
class PartyRole
include Mongoid::Document
include Mongoid::Timestamps
# Enable subclassing on the Party base class
belongs_to :role_castable, polymorphic: true
belongs_to :party_role_kind,
class_name: "Parties::PartyRoleKind"
belongs_to :party_relationship,
class_name: 'Parties::PartyRelationship',
optional: true
# Date this role becomes effective for subject party
field :start_date, type: Date, default: ->{ TimeKeeper.date_of_record }
# Date this role is no longer in effect for subject_party
field :end_date, type: Date
validates_presence_of :party_role_kind, :start_date
# validate :validate_related_party
delegate :key, to: :party_role_kind, allow_nil: true
delegate :title, to: :party_role_kind, allow_nil: true
delegate :description, to: :party_role_kind, allow_nil: true
# delegate :party_relationship_kinds, to: :party_role_kind, allow_nil: true
# delegate :eligibility_policy, to: :party_role_kind, allow_nil: true
# def add(role_kind_key)
# role_kind = Parties::PartyRoleKind.find_by(key: :role_kind_key)
# end
def is_active?
end_date.blank? || end_date > TimeKeeper.date_of_record
end
# Deactive this role
def terminate(new_end_date = TimeKeeper.date_of_record)
related_party.end_role(new_end_date) if related_party.present?
write_attribute(:end_date, new_end_date)
end
# Restore a deactiviated role
def reinstate
related_party.reinstate_role(new_end_date) if related_party.present?
write_attribute(:end_date, nil)
end
# def party_role_kind=(new_party_role_kind)
# if new_party_role_kind.nil?
# write_attribute(:new_party_role_kind, nil)
# else
# raise ArgumentError.new("expected Parties::PartyRoleKind") unless new_party_role_kind.is_a? Parties::PartyRoleKind
# write_attribute(:party_role_kind_id, new_party_role_kind._id)
# end
# @party_role_kind = new_party_role_kind
# end
# def party_role_kind
# return nil if party_role_kind_id.blank?
# return @party_role_kind if defined? @party_role_kind
# @party_role_kind = Parties::PartyRoleKind.find(party_role_kind_id)
# end
# # Setter for Party instance associated through this Role
# def related_party=(new_related_party)
# if new_related_party.nil?
# write_attribute(:new_related_party, nil)
# else
# raise ArgumentError.new("expected Parties::Party") unless new_related_party.is_a? Parties::Party
# write_attribute(:related_party_id, new_related_party._id)
# end
# @related_party = new_related_party
# end
# # Getter for Party instance associated through this Role
# def related_party
# return nil if related_party_id.blank?
# return @related_party if defined? @related_party
# @related_party = Parties::Party.find(related_party_id)
# end
private
def validate_related_party
if party_relationship_kinds.present?
errors.add(:related_party, "party_role #{title} requires a related party instance") if related_party.blank?
errors.add(:related_party, "party_role #{title} related party kinds #{party_relationship_kinds.inspect} don't match party_relationship definition") unless party_roles_match?
else
errors.add(:related_party, "unexpected related_party #{related_party.inspect} for party_role #{title}") if related_party.present?
end
end
# Party roles must match
# Compare Roles for this and associated party
def party_roles_match?
return false if related_party.blank?
#TODO Develop validation for valid role-to-role relationship pairing
true
end
end
end
|
ipublic/marketplace
|
app/models/sagas/saga.rb
|
# The Saga pattern solves for long-lived, distributed transactions without using two-pase commit.
# Each activity in a workflow must succeed in order for the overarching transaction
# to succeed. If a component-level activity fails, any preceding activities are reversed
class Sagas::Saga
RESERVATION_ROUTING_SLIP = [
# Sagas::Activities::ReserveCarActivity.new(args),
# Sagas::Activities::ReserveHotelActivity.new(args),
# Sagas::Activities::ReserveFlightActivity.new(args)
]
RESERVATION_ACTIVITY_SERVICES = [
# Sagas::Activities::ReserveCarActivityService,
# Sagas::Activities::ReserveHotelActivityService,
# Sagas::Activities::ReserveFlightActivityService
]
def initialize(routing_slip = [])
@processes ||= RESERVATION_ACTIVITY_SERVICES
@routing_slip = routing_slip || Sagas::RoutingSlip.new(RESERVATION_ROUTING_SLIP)
@initial_uri = @routing_slip.progress_uri
send_message
end
def send_message
process = @processes.detect { |process| process.accept_message?(@initial_uri, @routing_slip) }
if process.present?
process(@initial_uri, @routing_slip)
else
raise StandardError.new "unrecognized uri for initial process: #{@uri} in processes: #{@processes}"
end
end
end
|
ipublic/marketplace
|
spec/factories/wages_wage_report_factories.rb
|
<reponame>ipublic/marketplace
FactoryBot.define do
factory :wages_wage_report_factory, class: 'Wages::WageReportFactory' do
end
end
|
ipublic/marketplace
|
app/models/current.rb
|
<reponame>ipublic/marketplace
class Current < ActiveSupport::CurrentAttributes
attribute :account, :user
attribute :request_id, :user_agent, :ip_address
resets { Time.zone = nil }
end
|
ipublic/marketplace
|
app/jobs/sell_cupcake_job.rb
|
class SellCupcakeJob < ApplicationJob
queue_as :default
def perform(cupcakes = [])
json_api_opts = {}
json_api_opts[is_collection: true]
json_api_opts[:meta] = {total: cupcakes.length }
serializer = CupcakeSerializer.new(cupcakes, json_api_opts)
message = serializer.serialized_json
ActiveJob::Base.execute message
ack!
end
end
|
ipublic/marketplace
|
app/models/notices/ui_blocked_claim_eligible_notice.rb
|
<filename>app/models/notices/ui_blocked_claim_eligible_notice.rb
class Notices::UiBlockedClaimEligibleNotice
include Mongoid::Document
end
|
ipublic/marketplace
|
app/models/parties/person_party.rb
|
module Parties
class PersonParty < Party
GENDER_KINDS = %W(male female)
field :business_title, type: String
field :current_first_name, type: String
field :current_middle_name, type: String
field :current_last_name, type: String
field :current_name_pfx, type: String
field :current_name_sfx, type: String
field :ssn, type: String
field :gender, type: String
field :dob, type: Date
# delegate :party_relationships, to: :party_roles
embeds_many :person_names,
class_name: "Parties::PersonName"
validates_presence_of :current_first_name, :current_last_name
#validates :ssn, uniqueness: true, allow_blank: true
validates :gender,
allow_blank: true,
inclusion: { in: GENDER_KINDS, message: "%{value} is not a valid gender" }
index({current_last_name: 1, current_first_name: 1})
index({current_first_name: 1, current_last_name: 1})
index({ssn: 1}, {sparse: true})
index({dob: 1}, {sparse: true})
scope :employed_by, -> (party){} # party_relationship of employment, with
scope :contact_for, -> (party){}
def hide_ssn
if self.ssn
self.ssn.split('')[5..8].unshift("x","x-","x","x","x-").join('')
else
""
end
end
end
end
|
ipublic/marketplace
|
app/models/cases/ui_blocked_claim_case.rb
|
module Cases
class UiBlockedClaimCase
include Mongoid::Document
end
end
|
ipublic/marketplace
|
app/models/fees/tax.rb
|
class Fees::Tax
include Mongoid::Document
end
|
ipublic/marketplace
|
app/models/cases/case.rb
|
module Cases
class Case
include Mongoid::Document
belongs_to :party,
class_name: 'Parties;:Party'
end
end
|
ipublic/marketplace
|
spec/factories/integrations_get_offers_in_compromises.rb
|
<reponame>ipublic/marketplace
FactoryBot.define do
factory :integrations_get_offers_in_compromise, class: 'Integrations::GetOffersInCompromise' do
end
end
|
ipublic/marketplace
|
spec/factories/financial_accounts_pfl_financial_accounts.rb
|
<gh_stars>0
FactoryBot.define do
factory :financial_accounts_pfl_financial_account, class: 'FinancialAccounts::PflFinancialAccount' do
end
end
|
ipublic/marketplace
|
spec/factories/fees_fees.rb
|
<gh_stars>0
FactoryBot.define do
factory :fees_fee, class: 'Fees::Fee' do
end
end
|
ipublic/marketplace
|
app/controllers/api/v3/echo_controller.rb
|
class Api::V3::EchoController < ApplicationController
before_action :shout_out
def show
# render json: @echo
end
private
def shout_out
@echo =
{
id: 54321,
message: "Hello World!",
}
end
end
|
ipublic/marketplace
|
app/models/taxes/tax.rb
|
<filename>app/models/taxes/tax.rb
class Taxes::Tax
include Mongoid::Document
end
|
ipublic/marketplace
|
app/models/dispatcher/job.rb
|
module Dispatcher
class Job
include Mongoid::Document
include Mongoid::Timestamps
# embedded_in
end
end
|
ipublic/marketplace
|
app/models/financial_accounts/financial_account_factory.rb
|
module FinancialAccounts
class FinancialAccountFactory
UI_FINANCIAL_ACCOUNT_KIND = :ui_financial_account
PFL_FINANCIAL_ACCOUNT_KIND = :pfl_financial_account
attr_accessor :financial_account
def self.call(party, args)
new(party, args).financial_account
end
def initialize(party, args)
@party = party
@account_kind = args[:account_kind]
@initial_liability_date = args[:initial_liability_date]
@ledger = nil
@financial_account = nil
@determination_service = nil
build_or_find_party_ledger
initialize_determination_service
build_or_find_ui_financial_account if @account_kind == UI_FINANCIAL_ACCOUNT_KIND
end
def build_or_find_party_ledger
if @party.party_ledger.present?
@ledger = @party.party_ledger
else
@ledger = @party.build_party_ledger
end
end
def initialize_determination_service
@determination_service = Determinations::UiDeterminationService.new(party: @party)
end
def build_or_find_ui_financial_account
if @ledger.financial_accounts.present?
@financial_account = @ledger.ui_financial_account
else
@financial_account = build_ui_financial_account
initialize_ui_financial_account
end
end
def build_ui_financial_account
title = "#{@party.legal_name}'s Unemployment Insurance Account"
opened_on = TimeKeeper.date_of_record
FinancialAccounts::UiFinancialAccount.new(party_ledger: @ledger, title: title, opened_on: opened_on)
end
def initialize_ui_financial_account
@financial_account.initial_liability_date = @initial_liability_date || @determination_service.initial_liability_date
@financial_account.current_payment_kind = @determination_service.payment_kind
@financial_account.current_wage_filing_schedule = @determination_service.wage_filing_schedule
@financial_account.current_administrative_rate = @determination_service.administrative_rate
@financial_account.current_contribution_rate = @determination_service.contribution_rate
@financial_account.financial_transactions << initial_transaction
end
def initial_transaction
title = 'opening balance'
kind = :credit
amount = 0.0
::FinancialAccounts::FinancialTransaction.new(title: title, kind: kind, amount: amount)
end
end
end
|
ipublic/marketplace
|
app/models/parties/party_role_kind.rb
|
<reponame>ipublic/marketplace
# Actor roles or categories that a Party entity plays in the context of the enterprise.
module Parties
class PartyRoleKind
include Mongoid::Document
include Mongoid::Timestamps
field :key, type: Symbol
field :title, type: String
field :description, type: String
# Used for enabling/disabling role kinds over time
field :is_published, type: Boolean, default: true
field :start_date, type: Date, default: ->{ TimeKeeper.date_of_record }
field :end_date, type: Date
has_and_belongs_to_many :party_relationship_kinds,
class_name: "Parties::PartyRelationshipKind"
has_many :party_roles,
class_name: 'Parties::PartyRole'
# Associate a business rule for validating a role instance
belongs_to :eligibility_policy,
class_name: 'EligibilityPolicies::EligibilityPolicy',
optional: true
before_validation :assign_key_and_title
validates_presence_of :key, :title, :start_date, :is_published
validates_uniqueness_of :key
index({ key: 1}, { unique: true })
index({ is_published: 1, start_date: 1, end_date: 1 })
# before_validation :set_key
alias_method :is_published?, :is_published
def has_party_relationship_kinds?
party_relationship_kinds.size > 0
end
def key=(new_key)
write_attribute(:key, text_to_symbol(new_key))
end
def publish
write_attribute(:is_published, true)
end
def unpublish
write_attribute(:is_published, false)
end
def is_draft?
!is_published?
end
private
def assign_key_and_title
write_attribute(:key, text_to_symbol(title)) if key.blank? && title.present?
write_attribute(:title, symbol_to_text(key)) if title.blank? && key.present?
end
def text_to_symbol(text)
text.to_s.parameterize.underscore.to_sym
end
def symbol_to_text(symbol)
symbol.to_s.titleize
end
def self.is_valid_key?(key)
all.pluck(:key).include?(key)
end
end
end
|
ipublic/marketplace
|
lib/account_middleware.rb
|
<filename>lib/account_middleware.rb
# Rack Middleware extension that inspects the request string for an account value and populates
# CurrentAttributes with information based on the account
# Application URL includes the Account identifier as the first value
# in the request string. For example a request formatted as: '/34bc21a3f4e/employers'
# where '34bc21a3f4e' is the Account ID and 'employers' is an index route
class AccountMiddleware
def initialize(app)
@app = app
end
# Make code thread safe by duplicating self on call
def call(env)
dup._call(env)
end
def _call(env)
_, account_id, request_path = env["REQUEST_PATH"].split('/', 3)
# Only process if first element of resource request is numeric or hex indicating presence of
# an account_id. Otherwise, ignore and pass request along rack chain
if account_id =~ /^[0-9A-F]+$/i
# Current model class is ActiveSupport::CurrentAttributes subclass
# Store the User instance on user attribute
# if account = Account.find(account_id)
# Current.account = account
# else
# return [302, { "Location" => "/" }, []]
# end
#### User model substituted for Account model for prototype only ####
#### Expects design where Account has_many Users
if user = User.find(account_id)
Current.user = user
else
return [302, { "Location" => "/" }, []]
end
# Rewrite the env values to match pattern
env["SCRIPT_NAME"] = "/#{account_id}"
env["PATH_INFO"] = "/#{request_path}"
env["REQUEST_PATH"] = "/#{request_path}"
env["REQUEST_URI"] = "/#{request_path}"
end
@app.call(env)
end
end
|
ipublic/marketplace
|
spec/factories/dispatcher_tasks_tasks.rb
|
FactoryBot.define do
factory :dispatcher_tasks_task, class: 'Dispatcher::Tasks::Task' do
end
end
|
ipublic/marketplace
|
spec/factories/sagas_activities_activity_hosts.rb
|
<reponame>ipublic/marketplace
FactoryBot.define do
factory :sagas_activities_activity_host, class: 'Sagas::Activities::ActivityHost' do
end
end
|
ipublic/marketplace
|
spec/models/parties/party_role_kind_spec.rb
|
<reponame>ipublic/marketplace
require 'rails_helper'
RSpec.describe Parties::PartyRoleKind, type: :model, dbclean: :after_each do
it { is_expected.to be_mongoid_document }
it { is_expected.to have_timestamps }
it { is_expected.to have_fields(:key, :title, :description, :is_published, :start_date, :end_date)}
let(:key) { :happy_camper }
let(:title) { "Happy Camper" }
let(:params) do
{
key: key,
title: title,
}
end
describe "A new model instance" do
context "with no arguments" do
subject { described_class.new }
it "should not be valid" do
subject.validate
expect(subject).to_not be_valid
end
end
context "with no key and no title" do
subject { described_class.new(params.except(*[:key, :title])) }
it "should not be valid" do
subject.validate
expect(subject).to_not be_valid
expect(subject.errors[:key].first).to match(/can't be blank/)
end
end
context "with a key and no title" do
subject { described_class.new(params.except(:title)) }
it "should be valid" do
subject.validate
expect(subject).to be_valid
end
end
context "with no key and a title" do
subject { described_class.new(params.except(:key)) }
it "should be valid" do
subject.validate
expect(subject).to be_valid
end
end
context "with all required arguments" do
subject {described_class.new(params) }
it "should be valid" do
subject.validate
expect(subject).to be_valid
end
context "and it is saved" do
it "should save" do
expect(subject.save).to eq true
end
context "it should be findable" do
before { subject.save! }
it "should return the instance" do
expect(described_class.find(subject.id.to_s)).to eq subject
end
end
end
end
end
describe "Working with PartyRelationshipKinds" do
let(:battle_opponents_party_relationship_kind) { Parties::PartyRelationshipKind.new(key: :battle_opponents) }
let(:dating_partners_party_relationship_kind) { Parties::PartyRelationshipKind.new(key: :dating_partners) }
let(:party_relationhip_kinds) { [battle_opponents_party_relationship_kind, dating_partners_party_relationship_kind] }
end
end
|
ipublic/marketplace
|
app/models/wages/nonexempt_wage_entry.rb
|
module Wages
class NonexemptWageEntry < Wage
field :hours_worked, type: Integer
end
end
|
ipublic/marketplace
|
spec/factories/timespans_calendar_year_timespans.rb
|
<filename>spec/factories/timespans_calendar_year_timespans.rb
FactoryBot.define do
factory :timespans_calendar_year_timespan, class: 'Timespans::CalendarYearTimespan' do
year { TimeKeeper.date_of_record.year }
end
end
|
ipublic/marketplace
|
app/controllers/notifications_controller.rb
|
<gh_stars>0
class NotificationsController < ApplicationController
layout 'two_column'
before_action :authenticate_user!
end
|
ipublic/marketplace
|
spec/factories/dispatcher_activities_group_reinstate_activities.rb
|
<filename>spec/factories/dispatcher_activities_group_reinstate_activities.rb<gh_stars>0
FactoryBot.define do
factory :dispatcher_activities_group_reinstate_activity, class: 'Dispatcher::Activities::GroupReinstateActivity' do
end
end
|
ipublic/marketplace
|
app/models/financial_accounts/liability_ledger_account_balance.rb
|
<reponame>ipublic/marketplace<gh_stars>0
module FinancialAccounts
class LiabilityLedgerAccountBalance
include Mongoid::Document
end
end
|
ipublic/marketplace
|
app/models/notices/ui_delinquency_notice.rb
|
<filename>app/models/notices/ui_delinquency_notice.rb
class Notices::UiDelinquencyNotice
include Mongoid::Document
end
|
ipublic/marketplace
|
app/models/bakery/cupcake.rb
|
# frozen_string_literal: true
module Bakery
class Cupcake
include Mongoid::Document
include Mongoid::Timestamps
CAKE_KINDS = %w[ white chocolate yellow ].freeze
FROSTING_KINDS = %w[ vanilla chocolate strawberry banana grape cherry coconut ].freeze
field :cc_id, type: Integer
field :cake
field :frosting
embeds_many :sprinkles, class_name: 'Bakery::Sprinkle'
index({ cc_id: 1 })
scope :view_window, ->(skip_count, limit_count) { skip(skip_count).limit(limit_count) }
scope :order_by_cc_id, -> { order(:"cc_id".asc) }
end
end
|
ipublic/marketplace
|
spec/factories/financial_accounts_contribution_rates.rb
|
<filename>spec/factories/financial_accounts_contribution_rates.rb<gh_stars>0
FactoryBot.define do
factory :financial_accounts_contribution_rate, class: 'FinancialAccounts::ContributionRate' do
end
end
|
swt2-intro-exercise/rails-exercise-18-JonasZim
|
spec/features/author/list_authors_spec.rb
|
require 'rails_helper'
describe 'authors page', type: :feature do
it 'should render without error' do
visit '/authors'
end
it 'should have a table with the authors name' do
visit '/authors'
expect(page).to have_selector('table tr')
expect(page).to have_link 'New', href: new_author_path
end
it 'should have an delete button which deletes the chosen author' do
end
end
|
swt2-intro-exercise/rails-exercise-18-JonasZim
|
spec/features/author/new_author_spec.rb
|
require 'rails_helper'
describe "New author page", type: :feature do
it "should render withour error" do
visit new_author_path
end
it "should have text inputs for an author's first name, last name, and homepage" do
visit new_author_path
# these are the standard names given to inputs by the form builder
expect(page).to have_field('author[first_name]')
expect(page).to have_field('author[last_name]')
expect(page).to have_field('author[homepage]')
end
it "should create new table entry" do
visit new_author_path
page.fill_in('author[first_name]', with: 'Alan')
page.fill_in('author[last_name]', with: 'Turing')
page.fill_in('author[homepage]', with: 'http://wikipedia.org/Alan_Turing')
find('input[type="submit"]').click
end
it "should have a valid name" do
author = Author.new('first_name' => 'Alan', 'last_name' => '', 'homepage' => 'example.com')
expect(author).to_not be_valid
end
it "should throw errors if the entry is not valid" do
visit new_author_path
page.fill_in('author[first_name]', with: 'Alan')
page.fill_in('author[last_name]', with: 'Turing')
page.fill_in('author[homepage]', with: 'http://wikipedia.org/Alan_Turing')
find('input[type="submit"]').click
#i dont know how i get the infos i would like to get like the author_params
end
end
|
swt2-intro-exercise/rails-exercise-18-JonasZim
|
spec/models/author_spec.rb
|
require 'rails_helper'
RSpec.describe Author, type: :model do
it "should do sth" do
author = Author.new('first_name' => 'Alan', 'last_name'=>'Turing', 'homepage'=>'http://wikipedia.org/Alan_Turing')
expect(author.name).to eq('<NAME>')
expect(author.homepage).to eq('http://wikipedia.org/Alan_Turing')
end
end
|
iwat/codejam
|
case20201ac/gen.rb
|
100000.times do
puts 1000000
end
|
matti/kbe
|
lib/kbe/cli/version_command.rb
|
# frozen_string_literal: true
module KBE
module CLI
class VersionCommand < Clamp::Command
def execute
puts KBE::VERSION
end
end
end
end
|
matti/kbe
|
lib/kbe/cli/logs_command.rb
|
<gh_stars>0
# frozen_string_literal: true
module KBE
module CLI
class LogsCommand < Clamp::Command
option ['-h', '--help'], :flag, "help" do
puts "kbe delete selector"
exit 0
end
parameter "SELECTOR_OR_POD", "selector or pod name"
parameter "[CONTAINER]", "container"
def execute
pod = KBE.pod_by(selector_or_pod, only_running: false)
parts = []
parts << "logs --tail=10 -f #{pod}"
parts << "-c #{container}" if container # let error because it gives the list
KBE.kubectl parts.join(" ")
end
end
end
end
|
matti/kbe
|
lib/kbe/cli/root_command.rb
|
# frozen_string_literal: true
require_relative "version_command"
require_relative "help_command"
require_relative "enter_command"
require_relative "list_command"
require_relative "delete_command"
require_relative "logs_command"
require_relative "attach_command"
module KBE
module CLI
class RootCommand < Clamp::Command
banner "kbe 🍻"
option ['-v', '--version'], :flag, "Show version information" do
puts KBE::VERSION
exit(0)
end
subcommand ["list"], "List pods", ListCommand
subcommand ["enter"], "Enter a container", EnterCommand
subcommand ["attach"], "Attach to a container", AttachCommand
subcommand ["logs"], "Get logs", LogsCommand
subcommand ["delete"], "Delete a pod", DeleteCommand
subcommand ["version"], "Show version information", VersionCommand
subcommand ["help"], "Show help", HelpCommand
def self.run
super
rescue StandardError => exc
warn exc.message
warn exc.backtrace.join("\n")
end
end
end
end
|
matti/kbe
|
lib/kbe/cli/help_command.rb
|
<filename>lib/kbe/cli/help_command.rb
# frozen_string_literal: true
module KBE
module CLI
class HelpCommand < Clamp::Command
def execute
exec "kbe -h"
end
end
end
end
|
matti/kbe
|
lib/kbe/cli.rb
|
<gh_stars>0
require 'clamp'
Clamp.allow_options_after_parameters = true
module KBE
module CLI
end
end
require_relative 'cli/root_command'
|
matti/kbe
|
lib/kbe/cli/attach_command.rb
|
<reponame>matti/kbe
# frozen_string_literal: true
module KBE
module CLI
class AttachCommand < Clamp::Command
option ['-h', '--help'], :flag, "help" do
puts "kbe attach myapp"
exit 0
end
option ['-c', '--container'], 'CONTAINER', 'container', default: :first
parameter "SELECTOR_OR_POD", "selector or pod name"
def execute
pod = KBE.pod_by selector_or_pod
args = []
args << "attach -it #{pod}"
unless container == :first
args << "-c #{container}"
end
KBE.kubectl args
end
end
end
end
|
matti/kbe
|
lib/kbe.rb
|
<reponame>matti/kbe<gh_stars>0
require "colorize"
module KBE
class Error < StandardError; end
def self.kubectl(*args)
cmd = []
cmd << "kubectl"
cmd << args
cmd_string = cmd.join " "
STDERR.puts cmd_string.colorize(:light_black)
exec cmd_string
end
def self.pod_by(name_or_selector, only_running: true)
pods = if name_or_selector.match? "="
get_pods selector: name_or_selector, only_running: only_running
else
get_pods name: name_or_selector, only_running: only_running
end
if pods.empty?
["app", "job-name"].each do |selector_prefix|
magic_selector = "#{selector_prefix}=#{name_or_selector}"
pods = get_pods selector: magic_selector, only_running: only_running
break if pods.any?
end
end
if pods.size == 1
return pods.first
elsif pods.size > 1
STDERR.puts "too many pods found:"
STDERR.p pods
else
STDERR.puts "no pods found."
end
exit 1
end
def self.get_pods(selector:nil, name:nil, only_running: true)
parts = []
parts << "kubectl get pods --no-headers -o custom-columns=':metadata.name'"
if selector
parts << "--field-selector=status.phase=Running" if only_running
parts << "--selector=#{selector}"
else
parts << name
end
cmd = parts.join " "
# dev/null supresses the "pod not found" by name
`#{cmd} 2>/dev/null`.split("\n")
end
end
require_relative 'kbe/version'
require_relative 'kbe/cli'
|
matti/kbe
|
lib/kbe/cli/delete_command.rb
|
# frozen_string_literal: true
require "json"
module KBE
module CLI
class DeleteCommand < Clamp::Command
option ['-h', '--help'], :flag, "help" do
puts "kbe delete selector"
exit 0
end
parameter "SELECTOR_OR_POD", "selector or pod name"
def execute
pod = KBE.pod_by(selector_or_pod, only_running: false)
KBE.kubectl "delete pod #{pod}"
end
end
end
end
|
matti/kbe
|
lib/kbe/cli/list_command.rb
|
<filename>lib/kbe/cli/list_command.rb
# frozen_string_literal: true
require "json"
module KBE
module CLI
class ListCommand < Clamp::Command
option ['-h', '--help'], :flag, "help" do
puts "kbe list"
puts "kbe list pod"
exit 0
end
parameter "[POD]", "list containers from pod", attribute_name: :selector
def execute
if selector
pod = KBE.pod_by(selector, only_running: false)
json = JSON.parse(`kubectl get pod #{pod} -o json`)
for container in json["spec"]["containers"]
puts container["name"]
end
else
KBE.kubectl ["get pod"]
end
rescue JSON::ParserError
end
end
end
end
|
mediamonks/MMMocking
|
MMMocking.podspec
|
<gh_stars>0
#
# MMMocking. Part of MMMTemple.
# Copyright (C) 2015-2020 MediaMonks. All rights reserved.
#
Pod::Spec.new do |s|
s.name = "MMMocking"
s.version = "0.1.4"
s.summary = "Mock data using hip lorem ipsum and pseudo random numbers"
s.description = s.summary
s.homepage = "https://github.com/mediamonks/#{s.name}"
s.license = "MIT"
s.authors = "MediaMonks"
s.source = { :git => "https://github.com/mediamonks/#{s.name}.git", :tag => s.version.to_s }
s.ios.deployment_target = '11.0'
s.subspec 'ObjC' do |ss|
ss.source_files = [ "Sources/#{s.name}ObjC/*.{h,m}" ]
end
s.swift_versions = '4.2'
s.static_framework = true
s.pod_target_xcconfig = {
"DEFINES_MODULE" => "YES"
}
s.subspec 'Swift' do |ss|
ss.source_files = [ "Sources/#{s.name}/*.swift" ]
ss.dependency "#{s.name}/ObjC"
end
s.test_spec 'Tests' do |ss|
ss.source_files = "Tests/*.{m,swift}"
end
s.default_subspec = 'ObjC', 'Swift'
end
|
nhayes-roth/sample_app
|
test/models/user_test.rb
|
<filename>test/models/user_test.rb
require 'test_helper'
class UserTest < ActiveSupport::TestCase
def setup
@user = users(:user1)
end
test "should be valid" do
user = User.new(name: "Example User", email: "<EMAIL>", password: "password", password_confirmation: "password")
assert user.valid?
end
# Field presence validation
test "name should be present" do
user = User.new(name: " ", email: "<EMAIL>", password: "password", password_confirmation: "password")
assert_not user.valid?
end
test "email should be present" do
user = User.new(name: "Foo", email: " \t", password: "password", password_confirmation: "password")
assert_not user.valid?
end
test "password should be present" do
user = User.new(name: "Foo", email: "<EMAIL>", password: "", password_confirmation: "")
assert_not user.valid?
end
# Field length validation
test "name should be short enough" do
user = User.new(name: "f" * 100, email: "<EMAIL>", password: "password", password_confirmation: "password")
assert_not user.valid?
end
test "email should be short enough" do
user = User.new(name: "Foo", email: "f" * 100 + "@foo.com", password: "password", password_confirmation: "password")
assert_not user.valid?
end
test "password should be long enough" do
user = User.new(name: "Foo", email: "<EMAIL>", password: "pw", password_confirmation: "pw")
assert_not user.valid?
end
# Email format validation
test "valid emails should pass" do
assert User.new(name: "foo", email: "<EMAIL>", password: "password", password_confirmation: "password").valid?
assert User.new(name: "foo", email: "<EMAIL>", password: "password", password_confirmation: "password").valid?
assert User.new(name: "foo", email: "<EMAIL>", password: "password", password_confirmation: "password").valid?
assert User.new(name: "foo", email: "<EMAIL>", password: "password", password_confirmation: "password").valid?
assert User.new(name: "foo", email: "<EMAIL>", password: "password", password_confirmation: "password").valid?
assert User.new(name: "foo", email: "<EMAIL>", password: "password", password_confirmation: "password").valid?
assert User.new(name: "foo", email: "<EMAIL>", password: "password", password_confirmation: "password").valid?
end
test "invalid emails should be rejected" do
assert_not User.new(name: "foo", email: "<EMAIL>", password: "password", password_confirmation: "password").valid?
assert_not User.new(name: "foo", email: " <EMAIL>", password: "password", password_confirmation: "password").valid?
assert_not User.new(name: "foo", email: "foo @ bar.<EMAIL>", password: "password", password_confirmation: "password").valid?
assert_not User.new(name: "foo", email: "<EMAIL> om", password: "password", password_confirmation: "password").valid?
assert_not User.new(name: "foo", email: "foo.at.bar.com", password: "password", password_confirmation: "password").valid?
assert_not User.new(name: "foo", email: "<EMAIL>", password: "password", password_confirmation: "password").valid?
assert_not User.new(name: "foo", email: "<EMAIL>", password: "password", password_confirmation: "password").valid?
end
test "emails must be unique" do
# Create and save a user with a given email
user1 = User.create(name: "foo", email: "<EMAIL>", password: "password", password_confirmation: "password")
assert user1.valid?
# Attempting to create another user with the same email should fail (case insensitive)
user2 = User.new(name: "foo", email: "<EMAIL>", password: "password", password_confirmation: "password")
assert user1.valid?
assert_not user2.valid?
# Destroying the original user allows the new user to pass validation
user1.destroy
assert user2.valid?
end
test "emails are downcased on save" do
user = User.create(name: "foo", email: "<EMAIL>", password: "password", password_confirmation: "password")
assert_equal(user.email, "<EMAIL>")
end
test "nil digest should not throw" do
remember_token = @user.update_remember_digest
assert @user.authenticated?(remember_token)
@user.forget_remember_digest
assert_not @user.authenticated?(remember_token)
end
end
|
nhayes-roth/sample_app
|
app/models/user.rb
|
class User < ApplicationRecord
attr_accessor(:remember_token)
before_save { self.email = email.downcase }
validates(
:name,
{
presence: true,
length: { maximum: 99 }
})
validates(
:email,
{
presence: true,
length: { maximum: 99 },
format: { with: /\A[\w+\-.]+@([a-z\d\-]+\.)+[a-z]+\z/i },
uniqueness: { case_sensitive: false }
})
validates(
:password,
{
presence: true,
length: { minimum: 5 },
# Allows accounts to be edited without re-specifying the password
allow_nil: true,
})
has_secure_password
# Class method that computes the secure hash transformation of a given string (password)
def User.digest(string)
# Use the minimum cost in tests and a normal (high) cost in production
cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
BCrypt::Engine.cost
return BCrypt::Password.create(string, cost: cost)
end
def User.new_token()
return SecureRandom.urlsafe_base64();
end
# Generates a new remember_digest to remember this user (i.e. when they login).
# Returns the corresponding remember_token for use in cookies.
def update_remember_digest()
remember_token = User.new_token();
update_attribute(:remember_digest, User.digest(remember_token));
return remember_token
end
# Wipes the remember_digest for this user (i.e. when they logout.)
def forget_remember_digest()
update_attribute(:remember_digest, nil);
return self;
end
# Returns whether the specified remember_token matches the stored digest
def authenticated?(signed_remember_token)
return remember_digest.nil? ? false
: BCrypt::Password.new(remember_digest)
.is_password?(signed_remember_token)
end
end
|
nhayes-roth/sample_app
|
test/integration/users_edit_account_settings_test.rb
|
<filename>test/integration/users_edit_account_settings_test.rb
require 'test_helper'
class UsersEditAccountSettingsTest < ActionDispatch::IntegrationTest
def setup
@user1 = users(:user1)
@user2 = users(:user2)
end
test "update success same password" do
login()
get edit_user_path(@user1)
assert_no_difference 'User.count' do
patch(
user_path(@user1),
params: {
user: {
name: "<NAME>",
email: "<EMAIL>",
password: "password",
password_confirmation: "password"
}
})
end
assert_redirected_to @user1
follow_redirect!
assert_template 'users/show'
updated_user = User.find(@user1.id)
assert_equal updated_user.name, "<NAME>"
assert_equal updated_user.email, "<EMAIL>"
assert updated_user.authenticate("password")
assert_select "div.alert-success", UsersController::UPDATE_SUCCESS
end
test "update success empty password" do
login()
get edit_user_path(@user1)
assert_no_difference 'User.count' do
patch(
user_path(@user1),
params: {
user: {
name: "<NAME>",
email: "<EMAIL>",
password: "",
password_confirmation: ""
}
})
end
assert_redirected_to @user1
follow_redirect!
assert_template 'users/show'
updated_user = User.find(@user1.id)
assert_equal updated_user.name, "<NAME>"
assert_equal updated_user.email, "<EMAIL>"
assert updated_user.authenticate("<PASSWORD>")
assert_select "div.alert-success", UsersController::UPDATE_SUCCESS
end
test "update success new password" do
login()
get edit_user_path(@user1)
assert_no_difference 'User.count' do
patch(
user_path(@user1),
params: {
user: {
name: "<NAME>",
email: "<EMAIL>",
password: "<PASSWORD>",
password_confirmation: "new password"
}
})
end
assert_redirected_to @user1
follow_redirect!
assert_template 'users/show'
updated_user = User.find(@user1.id)
assert_equal updated_user.name, "<NAME>"
assert_equal updated_user.email, "<EMAIL>"
assert updated_user.authenticate("new password")
assert_select "div.alert-success", UsersController::UPDATE_SUCCESS
end
test "failure invalid" do
login()
get edit_user_path(@user1)
assert_no_difference 'User.count' do
patch(
user_path(@user1),
params: {
user: {
name: "<NAME>",
email: "new_email@invalid email dot com",
password: "",
password_confirmation: ""
}
})
end
assert_template 'users/edit'
unchanged_user = User.find(@user1.id)
assert_equal unchanged_user.name, @user1.name
assert_equal unchanged_user.email, @user1.email
assert_select "div.alert-danger", 1
assert_select 'div#error_explanation', 1
assert_select 'div.field_with_errors', 2
end
test "failure not logged in unauthorized" do
get edit_user_path(@user1)
assert_response :redirect
assert_redirected_to login_path
patch(
user_path(@user1),
params: {
user: {
name: "<NAME>",
email: "<EMAIL>",
password: "",
password_confirmation: ""
}
})
assert_response :redirect
assert_redirected_to login_path
unchanged_user = User.find(@user1.id)
assert_equal unchanged_user.name, @user1.name
assert_equal unchanged_user.email, @user1.email
end
test "failure logged in as different user unauthorized" do
login(email: @user2.email, password: '<PASSWORD>')
get edit_user_path(@user1)
assert_response :redirect
assert_redirected_to root_path
patch(
user_path(@user1),
params: {
user: {
name: "<NAME>",
email: "<EMAIL>",
password: "",
password_confirmation: ""
}
})
assert_response :redirect
assert_redirected_to root_path
unchanged_user = User.find(@user1.id)
assert_equal unchanged_user.name, @user1.name
assert_equal unchanged_user.email, @user1.email
end
end
|
nhayes-roth/sample_app
|
test/controllers/users_controller_test.rb
|
<reponame>nhayes-roth/sample_app<filename>test/controllers/users_controller_test.rb
require 'test_helper'
class UsersControllerTest < ActionDispatch::IntegrationTest
def setup
@user1 = users(:user1)
@user2 = users(:user2)
@admin = users(:admin)
end
################ Basic route tests ################
test "get new user sign up" do
get signup_path
assert_response :success
assert_select("title", full_title("Sign up"))
end
test "get login" do
get login_path
assert_response :success
assert_select("title", full_title("Login"))
end
test "get user profile" do
get(user_path(@user1))
assert_response(:success)
assert_select("title", full_title(@user1.name))
end
################ Basic (authenticated) route tests ################
test "get account settings when logged in" do
login
get edit_user_path(@user1)
assert_response :success
assert_select("title", full_title("Account Settings"))
end
test "get account settings when admin" do
login(email: @admin.email, password: 'password')
get edit_user_path(@user1)
assert_response :success
assert_select("title", full_title("Account Settings"))
end
test "get index when logged in" do
login
get(users_path)
assert_response(:success)
assert_select("title", full_title("Users"))
end
################ Basic (unauthenticated) route tests ################
test "get account settings redirects to login when logged out" do
get edit_user_path(@user1)
assert_response(:redirect)
assert_redirected_to(login_path)
end
test "get index redirects to login when logged out" do
get(users_path)
assert_response(:redirect)
assert_redirected_to login_path
end
test "should not allow the admin attribute to be edited via the web" do
login(email: @user2.email, password: '<PASSWORD>')
assert_not(@user2.admin?)
patch(
user_path(@user2),
params: {
user: {
admin: true
}
})
assert_not(@user2.reload.admin?)
end
end
|
nhayes-roth/sample_app
|
app/helpers/sessions_helper.rb
|
<gh_stars>0
module SessionsHelper
LOGIN_SUCCESS = 'Successfully logged in!'
# Logs the specified user in and updates the session's user.id and cookies.
def login(user, remember_me='1')
session[:user_id] = user.id
remember_via_cookies(user) if remember_me == '1'
return @user = current_user()
end
# Creates the cookies necessary to keep a user permanently logged in.
def remember_via_cookies(user)
remember_token = user.update_remember_digest()
cookies.permanent.signed[:user_id] = user.id
cookies.permanent.signed[:remember_token] = remember_token
end
# Exits the current session, logging the user out.
def logout(user)
session.delete(:user_id)
forget_via_cookies(user)
@current_user = nil
end
# Deletes the cookies necessary to 'forget' a user.
def forget_via_cookies(user)
user.forget_remember_digest() if logged_in?
cookies.delete(:user_id)
cookies.delete(:remember_token)
end
# Returns whether there is a user already logged in.
def logged_in?()
return !current_user().nil?
end
# Gets the currently logged in user (nil if none is logged in).
def current_user()
# Retrieve the user from the current session (if available)
if session[:user_id]
return @current_user ||= User.find_by_id(session[:user_id])
# Otherwise, check cookies for a persistent user that never logged out.
elsif cookies.signed[:user_id]
user = User.find_by_id(cookies.signed[:user_id]);
# Verify the cookie against the user's stored digest.
if user && user.authenticated?(cookies.signed[:remember_token])
return @current_user = user
else
return @current_user = nil
end
end
end
def record_original_request_url
session[:original_request_url] = request.original_url
end
# Redirects after a successful login
def redirect_after_login
if (!logged_in?)
raise
end
# If the original request caused a redirect to login, redirect to that initial location.
if !session[:original_request_url].nil?
redirect_to(session[:original_request_url], status: 303)
session.delete(:initial_request)
else
# Otherwise, default to the current user's profile page.
redirect_to(current_user)
end
# Always flash success.
flash[:success] = LOGIN_SUCCESS
end
end
|
nhayes-roth/sample_app
|
app/controllers/users_controller.rb
|
class UsersController < ApplicationController
before_action :check_logged_in, only: [:index, :edit, :update, :destroy]
before_action :check_authorized, only: [:edit, :update, :destroy]
DEFAULT_PAGE_SIZE = 25
MAX_PAGE_SIZE = 100
SIGNUP_SUCCESS = "Successfully signed up! Welcome!"
DESTROY_SUCCESS = "Successfully deleted account!"
UPDATE_SUCCESS = "Account settings updated!"
NOT_AUTHORIZED = "You are not authorized to view other users' pages."
BAD_PAGE_SIZE_WARNING = "Page size must be between [1, #{MAX_PAGE_SIZE}]."
# Action that lists all users
def index
params[:page_size] ||= DEFAULT_PAGE_SIZE
if (params[:page_size].to_i < 0 ||
params[:page_size].to_i > MAX_PAGE_SIZE)
params[:page_size] = DEFAULT_PAGE_SIZE
flash[:danger] = BAD_PAGE_SIZE_WARNING
redirect_to users_path(params.permit(:page, :page_size)) and return
end
@users =
User.paginate(page: params[:page], per_page: params[:page_size])
.order('id')
end
# Action that shows a user profile
def show
@user = User.find(params[:id])
end
# Action that generates a new user (i.e. before signup)
def new
@user = User.new
end
# Action that generates a new user with data (i.e. as a result of signup)
def create
@user = User.new(user_params)
if (@user.save())
login(@user)
redirect_to @user
flash[:success] = SIGNUP_SUCCESS
else
render 'new', status: 400
end
end
# Action that allows a user to update their account (before editing)
def edit
@user = User.find(params[:id])
end
def update
@user = User.find(params[:id])
if (@user.update_attributes(user_params))
redirect_to @user
flash[:success] = UPDATE_SUCCESS
else
render 'edit', status: 400
end
end
def destroy
User.find(params[:id]).destroy
@current_user = helpers.current_user
if !@current_user.nil? && @current_user.admin
redirect_to users_path
else
redirect_to root_path
end
flash.now[:success] = DESTROY_SUCCESS
end
private def check_logged_in
if !helpers.logged_in?
flash[:danger] = "Please log in."
helpers.record_original_request_url
redirect_to(login_url)
end
end
private def check_authorized
# Check if the logged in user (via cookies/session) matches the requested url.
if (!helpers.current_user.admin? &&
helpers.current_user.id.to_s != params[:id])
redirect_to(root_path)
flash[:danger] = 'You are not authorized to view other users\' pages.'
end
end
private def user_params
return params
.require(:user)
.permit(
:name,
:email,
:password,
:password_confirmation)
end
end
|
nhayes-roth/sample_app
|
config/environment.rb
|
<filename>config/environment.rb
# Load the Rails application.
require_relative 'application'
# Initialize the Rails application.
Rails.application.initialize!
# Configure logger
Rails.logger = ActiveSupport::Logger.new(STDOUT)
Rails.logger.level = Logger::INFO
|
nhayes-roth/sample_app
|
app/helpers/application_helper.rb
|
<filename>app/helpers/application_helper.rb
module ApplicationHelper
BASE_TITLE = "Ruby on Rails Tutorial Sample App"
# Returns an html page title, optionally adding a page-specific prefix
def full_title(page_title = "")
page_title.empty? ?
BASE_TITLE :
"#{page_title} | #{BASE_TITLE}"
end
end
|
nhayes-roth/sample_app
|
test/integration/users_authorization_redirect_test.rb
|
require 'test_helper'
class UsersAuthorizationRedirectTest < ActionDispatch::IntegrationTest
class Operation
attr_accessor(:description, :url, :operation)
def set_description(description)
@description = description
end
def set_url(url)
@url = url
end
def set_operation(lambda)
@operation = lambda
return self
end
end
def setup
@user = users(:user1)
@get_edit_user1 = Operation.new()
@get_edit_user1.set_description("get edit user1")
@get_edit_user1.set_url(edit_user_path(@user))
@get_edit_user1.set_operation(lambda { get(@get_edit_user1.url)})
@patch_user1 = Operation.new()
@patch_user1.set_description("patch user1")
@patch_user1.set_url("/users/1/edit")
@patch_user1.set_operation(
lambda {
patch(
@patch_user1.url,
params: {
user: {
name: "<NAME>",
email: "<EMAIL>",
password: "",
password_confirmation: ""
}
})})
@list_users = Operation.new()
@list_users.set_description("list users")
@list_users.set_url("/users")
@list_users.set_operation(lambda { get(@list_users.url) })
@requests = [
@get_edit_user1,
@patch_user1,
@list_users
]
end
test "redirects to initially requested page after login" do
@requests.each do |request|
puts "DEBUG - testing #{request.description}..."
# Logout to setup the test
logout
# Attempt unauthorized operation
request.operation.call
# Verify redirected to login
assert_response :redirect
assert_redirected_to login_path
# Login as user1
login
# Verify redirect to initially requested url after login
assert_response :redirect
assert_redirected_to request.url
end
end
test "redirects unauthorized user to root" do
[@get_edit_user1, @patch_user1].each do |request|
puts "DEBUG - testing #{request.description}..."
# Logout to setup the test
logout
# Attempt unauthorized operation
request.operation.call
# Verify redirected to login
assert_response :redirect
assert_redirected_to login_path
# Login as user2
login(email: users(:user2).email, password: "<PASSWORD>")
# Verify redirect to root
assert_response :redirect
assert_redirected_to request.url
follow_redirect!
assert_response :redirect
assert_redirected_to root_path
follow_redirect!
assert_select 'div.alert-danger', UsersController::NOT_AUTHORIZED
end
end
end
|
nhayes-roth/sample_app
|
test/integration/users_show_test.rb
|
<reponame>nhayes-roth/sample_app
require 'test_helper'
class UsersShowTest < ActionDispatch::IntegrationTest
def setup
@user1 = users(:user1)
@user2 = users(:user2)
end
test "get my profile logged in" do
login
get(user_path(@user1))
assert_select("a[href=?]", edit_user_path(@user1))
end
test "get profile not logged in" do
get(user_path(@user1))
assert_select("a[href=?]", edit_user_path(@user1), count: 0)
end
test "get other profile logged in" do
login
get(user_path(@user2))
assert_select("a[href=?]", edit_user_path(@user2), count: 0)
end
end
|
nhayes-roth/sample_app
|
app/controllers/sessions_controller.rb
|
class SessionsController < ApplicationController
def new
end
def create
# Fail fast if either param is empty.
if params[:session][:email].empty? or params[:session][:password].empty?
flash.now[:danger] = 'Please enter your email and password.'
render 'new'
return
end
# Check if the e-mail is associated with an account.
user = User.find_by_email(params[:session][:email].downcase)
if !user
flash.now[:danger] = "#{params[:session][:email].downcase} is not associated with an account."
render 'new'
return
end
# Authenticate the user and return depending on the result.
authenticated = user.authenticate(params[:session][:password])
if authenticated
login(user, params[:session][:remember_me])
redirect_after_login
return
else
flash.now[:danger] = 'Password is incorrect!'
render 'new'
return
end
end
def destroy
logout(helpers.current_user)
redirect_to root_url
flash[:success] = "Successfully logged out!"
end
end
|
nhayes-roth/sample_app
|
test/integration/users_login_test.rb
|
require 'test_helper'
class UsersLoginTest < ActionDispatch::IntegrationTest
def setup
@user = users(:user1)
end
test "empty params" do
params1 = {session: {email: "", password: ""}}
params2 = {session: {email: "", password: "<PASSWORD>"}}
params3 = {session: {email: @user.email, password: ""}}
for params in [params1, params2, params3]
get login_path
assert_template 'sessions/new'
post(
login_path,
params: params);
assert_template 'sessions/new'
assert_not flash.empty?
get root_path
assert flash.empty?
end
end
test "email not associated with account" do
params = {session: {email: "<EMAIL>", password: "<PASSWORD>"}}
get login_path
assert_template 'sessions/new'
post(
login_path,
params: params);
assert_template 'sessions/new'
assert_not flash.empty?
get root_path
assert flash.empty?
end
test "invalid password" do
params = {session: {email: @user.email, password: "<PASSWORD>"}}
get login_path
assert_template 'sessions/new'
post(
login_path,
params: params);
assert_template 'sessions/new'
assert_not flash.empty?
get root_path
assert flash.empty?
end
test "successful login" do
params = {session: {email: @user.email, password: '<PASSWORD>'}}
get login_path
assert_template 'sessions/new'
post(
login_path,
params: params);
assert_redirected_to @user
follow_redirect!
assert_template 'users/show'
assert_select "a[href=?]", login_path, count: 0
assert_select "a[href=?]", logout_path
assert_select "a[href=?]", user_path(@user)
end
test "successful login with remembering" do
params = {session: {email: @user.email, password: '<PASSWORD>', remember_me: '1'}}
get login_path
post(
login_path,
params: params);
assert is_logged_in?
assert_not_empty cookies[:user_id]
assert_not_empty cookies[:remember_token]
end
test "successful login without remembering" do
params = {session: {email: @user.email, password: '<PASSWORD>', remember_me: '0'}}
get login_path
assert_template 'sessions/new'
post(
login_path,
params: params);
assert is_logged_in?
assert_nil cookies[:user_id]
assert_nil cookies[:remember_token]
end
test "successful logout" do
# First, login as the test user.
params = {session: {email: @user.email, password: '<PASSWORD>'}}
post(
login_path,
params: params);
follow_redirect!
# Logout and verify.
delete(logout_path)
assert_redirected_to root_path
follow_redirect!
assert !is_logged_in?
assert_select "a[href=?]", login_path, count: 1
assert_select "a[href=?]", logout_path, count: 0
# Logout and verify again (e.g. if you had 2 browser windows open).
delete(logout_path)
assert_redirected_to root_path
follow_redirect!
assert !is_logged_in?
assert_select "a[href=?]", login_path, count: 1
assert_select "a[href=?]", logout_path, count: 0
end
end
|
nhayes-roth/sample_app
|
test/integration/users_index_test.rb
|
require 'test_helper'
class UsersIndexTest < ActionDispatch::IntegrationTest
def setup
@user1 = users(:user1)
@user2 = users(:user2)
@admin = users(:admin)
@users = [@user1, @user2, @admin].sort_by(&:id)
end
################ Basic route tests ################
test "get first page no params" do
login
get(users_path)
# Should have entries for each user (default page size > 3) and no next/prev link.
assert_select("a[href=?]", user_path(@user1))
assert_select("a[href=?]", user_path(@user2))
assert_select("a[href=?]", user_path(@admin))
assert_select("a[href=?]", users_path(page: 0), count: 0)
assert_select("a[href=?]", users_path(page: 2), count: 0)
end
test "get each page in order with params" do
login
# Page 1
# Should have the 1st user, a link to the next page, and no link to the prev page.
get(users_path(page: 1, page_size: 1))
assert_select(".user-index-entry a[href=?]", user_path(@users[0]))
assert_select(".next_page a[href=?]", users_path(page: 2, page_size: 1))
assert_select(".previous_page a[href=?]", '#')
# Page 2
# Should have the 2nd user, a link to the next page, and a link to the prev page.
get(users_path(page: 2, page_size: 1))
assert_select(".user-index-entry a[href=?]", user_path(@users[1]))
assert_select(".next_page a[href=?]", users_path(page: 3, page_size: 1))
assert_select(".previous_page a[href=?]", users_path(page: 1, page_size: 1))
# Page 3
# Should have the 3rd user, no link to the next page, and a link to the prev page.
get(users_path(page: 3, page_size: 1))
assert_select(".user-index-entry a[href=?]", user_path(@users[2]))
assert_select(".next_page a[href=?]", '#')
assert_select(".previous_page a[href=?]", users_path(page: 2, page_size: 1))
end
test "page size too big redirects" do
login
# Without page param
get(users_path(page_size: 1000))
assert_redirected_to(users_path(page_size: UsersController::DEFAULT_PAGE_SIZE))
follow_redirect!
# With page param
get(users_path(page: 1, page_size: 1000))
assert_redirected_to(users_path(page: 1, page_size: UsersController::DEFAULT_PAGE_SIZE))
follow_redirect!
end
test "page size too small redirects" do
login
# Without page param
get(users_path(page_size: -1))
assert_redirected_to(users_path(page_size: UsersController::DEFAULT_PAGE_SIZE))
follow_redirect!
# With page param
get(users_path(page: 1, page_size: -1))
assert_redirected_to(users_path(page: 1, page_size: UsersController::DEFAULT_PAGE_SIZE))
follow_redirect!
end
end
|
nhayes-roth/sample_app
|
config/routes.rb
|
Rails.application.routes.draw do
root 'static_pages#home'
# StaticPages
get '/about', to: 'static_pages#about'
get '/help', to: 'static_pages#help'
get '/home', to: 'static_pages#home'
get '/contact', to: 'static_pages#contact'
# Users
get '/signup', to: 'users#new'
post '/signup', to: 'users#create'
get '/users/:id/edit', to: 'users#edit'
patch '/users/:id/edit', to: 'users#update'
delete '/users/:id/edit', to: 'users#destroy'
resources :users
# Sessions
get '/login', to: 'sessions#new'
post '/login', to: 'sessions#create'
delete '/logout', to: 'sessions#destroy'
end
|
nhayes-roth/sample_app
|
test/integration/users_destroy_test_test.rb
|
<reponame>nhayes-roth/sample_app<filename>test/integration/users_destroy_test_test.rb
require 'test_helper'
class UsersDestroyTestTest < ActionDispatch::IntegrationTest
def setup
@admin = users(:admin)
@user1 = users(:user1)
@user2 = users(:user2)
end
test "delete my own account should succeed" do
login
delete(edit_user_path(@user1))
assert_redirected_to(root_path)
follow_redirect!
assert(User.find_by(email: @user1.email).nil?)
end
test "delete another account should fail" do
login
delete(edit_user_path(@user2))
assert_redirected_to(root_path)
follow_redirect!
assert(!User.find_by(email: @user2.email).nil?)
end
test "admin can delete another account" do
login(email: @admin.email, password: 'password')
delete(edit_user_path(@user2))
assert_redirected_to(users_path)
follow_redirect!
assert(User.find_by(email: @user2.email).nil?)
end
end
|
nhayes-roth/sample_app
|
test/helpers/sessions_helper_test.rb
|
<gh_stars>0
require 'test_helper'
class SessionsHelperTest < ActionView::TestCase
def setup
@user = users(:user1)
end
test "current user returns nil when not logged in" do
assert_nil current_user
end
test "current user returns user when logged in without cookies" do
login(@user, remember_me="1")
cookies.delete(:user_id)
cookies.delete(:remember_token)
assert_equal(@user, current_user())
end
test "current user returns user when logged in and remembered" do
login(@user, remember_me="1")
assert_equal(@user, current_user())
end
test "current user returns user when logged in but not remembered" do
login(@user, remember_me="0")
assert_equal(@user, current_user())
end
test "current user returns nil when logged in but token is wrong" do
login(@user, remember_me="1")
session.delete(:user_id)
@user.update_attribute(:remember_digest, User.digest(User.new_token()))
assert_nil current_user
end
test "current user returns nil when logged in digest is empty" do
login(@user, remember_me="1")
session.delete(:user_id)
@user.update_attribute(:remember_digest, nil)
assert_nil current_user
end
end
|
nhayes-roth/sample_app
|
test/test_helper.rb
|
<filename>test/test_helper.rb
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
require "minitest/reporters"
include ApplicationHelper
Minitest::Reporters.use!
class ActiveSupport::TestCase
# Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
fixtures :all
# Add more helper methods to be used by all tests here...
# Returns true of a test user is logged in
def is_logged_in?
return !session[:user_id].nil?
end
def login(
options={
email: users(:user1).email,
password: '<PASSWORD>'
})
get login_path
post(
login_path,
params: {
session: {
email: options[:email],
password: <PASSWORD>]
}
});
assert is_logged_in?
end
def logout
delete logout_path
assert !is_logged_in?
end
end
|
nhayes-roth/sample_app
|
test/controllers/sessions_controller_test.rb
|
require 'test_helper'
class SessionsControllerTest < ActionDispatch::IntegrationTest
test "should get login" do
get login_path
assert_response :success
end
# test "should create new session" do
# post login_path
# assert_response :success
# end
# test "should delete session" do
# delete logout_path
# assert_response :success
# end
end
|
djireland/ASDReviews
|
apple-store-web-crawler.ruby
|
#!/usr/bin/env ruby
require 'rubygems'
require 'hpricot'
require 'httparty'
require 'sqlite3'
class String
def string_between_markers marker1, marker2
self[/#{Regexp.escape(marker1)}(.*?)#{Regexp.escape(marker2)}/m, 1]
end
end
# MODIFY YOUR NATIVE LANGUAGE
NATIVE_LANGUAGE = 'en'
# MODIFY THIS HASH WITH YOUR APP SET (grab the itunes store urls & pull the id params)
software = {
# http://phobos.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=289923007&mt=8
'ApppleID ' => ARGV[1],
}
stores = [
# { :name => 'United States', :id => 143441, :language => 'en' },
{ :name => 'Australia', :id => 143460, :language => 'en' },
# { :name => 'United Kingdom', :id => 143444, :language => 'en' },
]
DEBUG = false
TRANSLATE_URL = "http://ajax.googleapis.com/ajax/services/language/translate?"
def translate(opts)
from = opts[:from] == 'auto' ? '' : opts[:from] # replace 'auto' with blank per Translate API
to = opts[:to]
result = HTTParty.get(TRANSLATE_URL, :query => { :v => '1.0', :langpair => "#{from}|#{to}", :q => opts[:text] })
raise result['responseDetails'] if result['responseStatus'] != 200
return result['responseData']['translatedText']
end
# return a rating/subject/author/body hash
def fetch_reviews(software_id, store, pageNo)
reviews = []
# TODO: parameterize type=Purple+Software
cmd = sprintf(%{curl -s -A "iTunes/9.2 (Macintosh; U; Mac OS X 10.6" -H "X-Apple-Store-Front: %s" } <<
%{'https://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=%s&} <<
%{pageNumber=%s&sortOrdering=1&type=Purple+Software' | xmllint --format --recover - 2>/dev/null},
store[:id],
software_id,
pageNo)
rawxml = `#{cmd}`
if defined?(DEBUG) && DEBUG == true
open("appreview.#{software_id}.#{store[:id]}.xml", 'w') { |f| f.write(rawxml) }
end
doc = Hpricot.XML(rawxml)
doc.search("Document > View > ScrollView > VBoxView > View > MatrixView > VBoxView:nth(0) > VBoxView > VBoxView").each do |e|
review = {}
strings = (e/:SetFontStyle)
meta = strings[2].inner_text.split(/\n/).map { |x| x.strip }
review[:authorid] = `echo \"#{strings[2]}\"|delimExtract "userProfileId=" "><b>";`.strip
# Note: Translate is sensitive to spaces around punctuation, so we make sure br's connote space.
review[:rating] = e.inner_html.match(/alt="(\d+) star(s?)"/)[1].to_i
review[:author] = meta[3].gsub("\'"," ").strip
review[:version] = meta[7][/Version (.*)/, 1].strip unless meta[7].nil?
review[:date] = meta[10].strip
review[:subject] = strings[0].inner_text.strip.gsub("\'"," ").strip
review[:body] = strings[3].inner_html.gsub("<br />", " ").gsub("\"","").gsub("\n"," ").gsub("\'"," ").strip
#puts "#{review[:authorid]}"
#exit
if ! store[:language].empty? && store[:language] != NATIVE_LANGUAGE
begin
review[:subject] = translate( :from => store[:language], :to => NATIVE_LANGUAGE, :text => review[:subject] )
review[:body] = translate( :from => store[:language], :to => NATIVE_LANGUAGE, :text => review[:body] )
rescue => e
if DEBUG
puts "** oops, cannot translate #{store[:name]}/#{store[:language]} => #{NATIVE_LANGUAGE}: #{e.message}"
end
end
end
reviews << review
end
reviews
end
begin
reviewCnt=0
db = SQLite3::Database.open "apple.db"
db.execute "CREATE TABLE IF NOT EXISTS Reviews(
Hash TEXT PRIMARY KEY,
AppleID INTEGER,
AuthorID TEXT,
Author TEXT,
Rating TEXT,
Version TEXT,
Date TEXT,
Subject TEXT,
Body TEXT,
StoreName TEXT);"
stm = db.prepare "SELECT AppleID from Details"
rs = stm.execute
row = rs.next
while (row = rs.next) do
software.keys.sort.each do |software_key|
stores.sort_by { |a| a[:name] }.each do |store|
for page in 0..200
row = row.join "\s"
reviews = fetch_reviews(row, store, page)
if reviews.any?
reviews.each_with_index do |review, index|
cmd = "echo \"#{row}#
{review[:authorid]}#{review[:subject]}#{review[:date]}\" | md5sum | awk {'print $1'}"
hash = `#{cmd}`.strip
data = sprintf(%{(\'%s\',\'%s\',\'%s\',\'%s\',\'%s\',\'%s\',\'%s\',\'%s\',\'%s\',\'%s\')},
hash,
row,
review[:authorid],
review[:author],
review[:rating],
review[:version],
review[:date],
review[:subject],
review[:body],
store[:name])
#puts "#{data}"
begin
db.execute "INSERT INTO Reviews VALUES #{data}"
rescue SQLite3::Exception => e
puts e
break
end
end
else
break
end
row = rs.next
reviewCnt = reviewCnt + 1
print "#{reviewCnt} Completed \r"
end
end
end
end
rescue SQLite3::Exception => e
puts "Exception Occured"
puts e
continue
ensure
stm.close if stm
db.close if db
end
|
SupportBee/omniauth-asana
|
lib/omniauth/strategies/asana.rb
|
<filename>lib/omniauth/strategies/asana.rb
require 'omniauth-oauth2'
module OmniAuth
module Strategies
class Asana < OmniAuth::Strategies::OAuth2
option :client_options, {
:site => 'https://app.asana.com',
:authorize_url => 'https://app.asana.com/-/oauth_authorize',
:token_url => 'https://app.asana.com/-/oauth_token'
}
def request_phase
super
end
def authorize_params
super.tap do |params|
if request.params['client_options']
params[:client_options] = request.params['client_options']
end
end
end
uid { raw_info['id'].to_s }
info do
{
'name' => raw_info['name'],
'email' => raw_info['email']
}
end
extra do
{ :raw_info => raw_info }
end
def raw_info
@raw_info ||= access_token.params['data']
end
end
end
end
|
pre-sniff/pre-sniff-objc
|
PreDemCocoa.podspec
|
<filename>PreDemCocoa.podspec
Pod::Spec.new do |s|
s.name = "PreDemCocoa"
s.version = `sh utils.sh get-release-version`
s.summary = "A short description of PreDemCocoa."
s.homepage = "https://github.com/pre-dem/pre-dem-cocoa"
s.license = "MIT"
s.author = { "qiniu" => "<EMAIL>" }
s.source = { :git => "https://github.com/pre-dem/pre-dem-cocoa.git", :tag => "v#{s.version}" }
s.ios.deployment_target = "8.0"
s.default_subspec = "Core"
s.subspec 'Core' do |cs|
cs.source_files = "PreDemCocoa/**/*.{h,m,mm,c,cpp}"
cs.public_header_files = 'PreDemCocoa/Public/*.h'
cs.libraries = "c++", "z"
cs.resource_bundles = { 'PREDResources' => 'PreDemCocoa/Resources/*.plist' }
cs.dependency "UICKeyChainStore"
end
end
|
shinwang1/sms-twilio-test
|
app/controllers/notifications_controller.rb
|
class NotificationsController < ApplicationController
rescue_from StandardError do |exception|
trigger_sms_alerts(exception)
end
def trigger_sms_alerts(e)
@alert_message = "
[This is a test] ALERT!
It appears the server is having issues.
Exception: #{e}.
Go to: http://newrelic.com for more details."
@image_url = "http://howtodocs.s3.amazonaws.com/new-relic-monitor.png"
@admin_list = YAML.load_file('config/administrators.yml')
@admin_list.each do |admin|
begin
phone_number = admin['phone_number']
send_message(phone_number, @alert_message, @image_url)
flash[:success] = "Exception: #{e}. Administrators will be notified."
rescue
flash[:alert] = "Something when wrong."
end
end
redirect_to '/'
end
def index
end
def server_error
raise 'A test exception'
end
private
def send_message(phone_number, alert_message, image_url)
@twilio_number = ENV['TWILIO_NUMBER']
@client = Twilio::REST::Client.new ENV['TWILIO_ACCOUNT_SID'], ENV['TWILIO_AUTH_TOKEN']
message = @client.account.messages.create(
:from => @twilio_number,
:to => phone_number,
:body => alert_message,
# US phone numbers can make use of an image as well.
# :media_url => image_url
)
puts message.to
end
end
|
krisf/refinerycms-inquiries
|
spec/factories/inquiry.rb
|
<gh_stars>0
FactoryGirl.define do
factory :inquiry, class: Refinery::Inquiries::Inquiry do
name "Refinery"
email "<EMAIL>"
message "Hello..."
end
end
|
krisf/refinerycms-inquiries
|
app/controllers/refinery/inquiries/admin/inquiries_controller.rb
|
module Refinery
module Inquiries
module Admin
class InquiriesController < ::Refinery::AdminController
crudify :'refinery/inquiries/inquiry',
:title_attribute => "name",
:order => "created_at DESC"
helper_method :group_by_date
before_filter :find_all_ham, :only => [:index]
before_filter :find_all_spam, :only => [:spam]
before_filter :get_spam_count, :only => [:index, :spam]
def index
@inquiries = @inquiries.with_query(params[:search]) if searching?
@inquiries = @inquiries.page(params[:page])
end
def spam
self.index
render :action => 'index'
end
def toggle_spam
find_inquiry
@inquiry.toggle!(:spam)
redirect_to :back
end
protected
def find_all_ham
@inquiries = Refinery::Inquiries::Inquiry.ham
end
def find_all_spam
@inquiries = Refinery::Inquiries::Inquiry.spam
end
def get_spam_count
@spam_count = Refinery::Inquiries::Inquiry.where(:spam => true).count
end
private
def inquiry_params
params.require(:inquiry).permit(:name, :phone, :message, :email)
end
end
end
end
end
|
krisf/refinerycms-inquiries
|
app/controllers/refinery/inquiries/inquiries_controller.rb
|
module Refinery
module Inquiries
class InquiriesController < ::ApplicationController
before_filter :find_page, only: [:create, :new]
before_filter :find_thank_you_page, only: :thank_you
def thank_you
end
def new
@inquiry = Inquiry.new
end
def create
@inquiry = Inquiry.new(inquiry_params)
if @inquiry.save
if @inquiry.ham? || Inquiries.send_notifications_for_inquiries_marked_as_spam
begin
InquiryMailer.notification(@inquiry, request).deliver
rescue
logger.warn "There was an error delivering an inquiry notification.\n#{$!}\n"
end
if Setting.send_confirmation?
begin
InquiryMailer.confirmation(@inquiry, request).deliver
rescue
logger.warn "There was an error delivering an inquiry confirmation:\n#{$!}\n"
end
end
end
redirect_to refinery.thank_you_inquiries_inquiries_path
else
render :action => 'new'
end
end
protected
def find_page
@page = Page.where(link_url: '/contact').first
end
def find_thank_you_page
@page = Page.where(link_url: '/contact/thank_you').first
end
private
def inquiry_params
params.require(:inquiry).permit(:name, :phone, :message, :email)
end
end
end
end
|
krisf/refinerycms-inquiries
|
app/models/refinery/inquiries/setting.rb
|
<gh_stars>0
require 'refinery/setting'
module Refinery
module Inquiries
class Setting < ::Refinery::Setting
class << self
def confirmation_body
find_or_set(:inquiry_confirmation_body,
"Thank you for your inquiry %name%,\n\nThis email is a receipt to confirm we have received your inquiry and we'll be in touch shortly.\n\nThanks."
)
end
def confirmation_subject(locale='en')
find_or_set(:"inquiry_confirmation_subject_#{locale}",
"Thank you for your inquiry",
scoping: "inquiries"
)
end
def confirmation_subject=(locales_subjects)
locales_subjects.each do |locale, subject|
set(:"inquiry_confirmation_subject_#{locale}", {
value: subject,
scoping: "inquiries"
})
end
end
def confirmation_message(locale='en')
find_or_set(:"inquiry_confirmation_message_#{locale}", confirmation_body, scoping: "inquiries")
end
def confirmation_message=(locales_messages)
locales_messages.each do |locale, message|
set(:"inquiry_confirmation_message_#{locale}", {
value: message,
scoping: "inquiries"
})
end
end
def notification_recipients
recipients = ((Role[:refinery].users.first.email rescue nil) if defined?(Role)).to_s
find_or_set(:inquiry_notification_recipients, recipients, scoping: "inquiries")
end
def notification_recipients=(recipients)
set(:inquiry_notification_recipients, {
value: recipients,
scoping: "inquiries"
})
end
def notification_subject
find_or_set(:inquiry_notification_subject, "New inquiry from your website", scoping: "inquiries")
end
def send_confirmation?
find_or_set(:inquiry_send_confirmation, true, scoping: "inquiries")
end
end
end
end
end
|
krisf/refinerycms-inquiries
|
app/models/refinery/inquiries/inquiry.rb
|
<reponame>krisf/refinerycms-inquiries
require 'refinery/core/base_model'
require 'filters_spam'
module Refinery
module Inquiries
class Inquiry < Refinery::Core::BaseModel
filters_spam message_field: :message,
email_field: :email,
author_field: :name,
other_fields: [:phone],
extra_spam_words: %w()
validates :name, presence: true, length: { maximum: 255 }
validates :email, format: {
with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
}, length: { maximum: 255 }
validates :message, presence: true
default_scope { order('created_at DESC') }
def self.latest(number = 7, include_spam = false)
include_spam ? limit(number) : ham.limit(number)
end
end
end
end
|
krisf/refinerycms-inquiries
|
spec/models/refinery/inquiries/setting_spec.rb
|
<reponame>krisf/refinerycms-inquiries<gh_stars>0
require 'spec_helper'
module Refinery
module Inquiries
describe Setting do
describe ".notification_recipients=" do
it "delegates to Refinery::Setting#set" do
expect(Refinery::Setting).to receive(:set).
with(:inquiry_notification_recipients, {
:value=>"some value",
:scoping=>"inquiries"
})
Refinery::Inquiries::Setting.notification_recipients = "some value"
end
end
end
end
end
|
krisf/refinerycms-inquiries
|
spec/features/refinery/inquiries/inquiries_spec.rb
|
<gh_stars>0
require "spec_helper"
module Refinery
module Inquiries
describe "inquiries" do
before(:each) do
# load in seeds we use in migration
Refinery::Inquiries::Engine.load_seed
end
context "when valid data" do
it "is successful" do
visit refinery.inquiries_new_inquiry_path
fill_in "Name", :with => "<NAME>"
fill_in "Email", :with => "<EMAIL>"
fill_in "Message", :with => "Hey, I'm testing!"
click_button "Send message"
page.current_path.should == refinery.thank_you_inquiries_inquiries_path
page.should have_content("Thank You")
within "#body_content" do
page.should have_content("We've received your inquiry and will get back to you with a response shortly.")
page.should have_content("Return to the home page")
page.should have_selector("a[href='/']")
end
Refinery::Inquiries::Inquiry.count.should == 1
end
end
context "when invalid data" do
let(:name_error_message) { "Name can't be blank" }
let(:email_error_message) { "Email is invalid" }
let(:message_error_message) { "Message can't be blank" }
it "is not successful" do
visit refinery.inquiries_new_inquiry_path
click_button "Send message"
page.current_path.should == refinery.inquiries_new_inquiry_path
page.should have_content("There were problems with the following fields")
page.should have_content(name_error_message)
page.should have_content(email_error_message)
page.should have_content(message_error_message)
page.should have_no_content("Phone can't be blank")
Refinery::Inquiries::Inquiry.count.should == 0
end
it "displays the error messages in the same order as the fields" do
visit refinery.inquiries_new_inquiry_path
click_button "Send message"
page.should have_content(/#{name_error_message}.+#{email_error_message}.+#{message_error_message}/m)
end
end
describe "privacy" do
context "when show contact privacy link setting set to false" do
before(:each) do
Refinery::Inquiries.config.stub(:show_contact_privacy_link).and_return(false)
end
it "won't show link" do
visit refinery.inquiries_new_inquiry_path
page.should have_no_content("We value your privacy")
page.should have_no_selector("a[href='/pages/privacy-policy']")
end
end
context "when show contact privacy link setting set to true" do
before(:each) do
Refinery::Inquiries.config.stub(:show_contact_privacy_link).and_return(true)
end
it "shows the link" do
visit refinery.inquiries_new_inquiry_path
page.should have_content("We value your privacy")
page.should have_selector("a[href='/pages/privacy-policy']")
end
end
end
describe "palceholders" do
context "when show placeholders setting set to false" do
before(:each) do
Refinery::Inquiries.config.stub(:show_placeholders).and_return(false)
end
it "won't show placeholders" do
visit refinery.inquiries_new_inquiry_path
page.should have_no_selector("input[placeholder]")
end
end
context "when show placeholders setting set to true" do
before(:each) do
Refinery::Inquiries.config.stub(:show_placeholders).and_return(true)
end
it "shows the placeholders" do
visit refinery.inquiries_new_inquiry_path
page.should have_selector("input[placeholder]")
end
end
end
describe "phone number" do
context "when show phone numbers setting set to false" do
before(:each) do
Refinery::Inquiries.config.stub(:show_phone_number_field).and_return(false)
end
it "won't show phone number" do
visit refinery.inquiries_new_inquiry_path
page.should have_no_selector("label", :text => 'Phone')
page.should have_no_selector("#inquiry_phone")
end
end
context "when show phone numbers setting set to true" do
before(:each) do
Refinery::Inquiries.config.stub(:show_phone_number_field).and_return(true)
end
it "shows the phone number" do
visit refinery.inquiries_new_inquiry_path
page.should have_selector("label", :text => 'Phone')
page.should have_selector("#inquiry_phone")
end
end
end
end
end
end
|
SmallTwoInn/XZTest
|
XZTest.podspec
|
<reponame>SmallTwoInn/XZTest<gh_stars>0
#
# Be sure to run `pod spec lint XZTest.podspec' to ensure this is a
# valid spec and to remove all comments including this before submitting the spec.
#
# To learn more about Podspec attributes see http://docs.cocoapods.org/specification.html
# To see working Podspecs in the CocoaPods repo see https://github.com/CocoaPods/Specs/
#
Pod::Spec.new do |s|
s.name = 'XZTest'
s.version = '0.0.1'
s.summary = 'A short description of XZTest'
s.description = 'A long long description of XZTest'
s.homepage = 'https://github.com/SmallTwoInn/XZTest'
s.license = "MIT"
s.author = { "up_learn" => "<EMAIL>" }
s.source = { :git => "https://github.com/SmallTwoInn/XZTest.git", :tag => "#{s.version}" }
s.source_files = 'Classes/**/*.{h,m}'
end
|
jirokun/csvutil
|
csvutil.rb
|
<gh_stars>0
require 'csv'
require 'optparse'
require 'fileutils'
require './lib/postgres.rb'
require './lib/oracle.rb'
opt = OptionParser.new
opt.version = '0.0.1'
options = {}
opt.on('-t DATABASE', '--target=DATABASE', 'Target database, postgres | oracle', ['postgres', 'oracle']) {|v| options[:target] = v }
opt.on('-h', '--header', 'Specify this option when header is in CSV') {|v| options[:header] = v }
opt.on('-n table_name', '--name table_name', 'Table name to import') {|v| options[:table_name] = v }
opt.on('-f FILE', '--file=FILE', 'CSV file to input') {|v| options[:file] = v }
opt.parse(ARGV)
raise "File must be specified" if options[:file].nil?
raise "File not found: #{options[:file]}" unless File.exists? options[:file]
header_str = nil
open(options[:file], 'r', encoding: 'cp932') { |f| header_str = f.gets.chomp.encode('utf-8') }
headers = CSV.parse_line(header_str)
FileUtils.mkdir_p(options[:table_name])
db = nil
if options[:target] == 'postgres'
db = Postgres.new options, headers
elsif options[:target] == 'oracle'
db = Oracle.new options, headers
else
STDERR.puts "Invalid usage. please #{$0} -h"
end
db.create_table
db.import_csv
db.drop_table
db.show_usage
|
jirokun/csvutil
|
lib/oracle.rb
|
<reponame>jirokun/csvutil
class Oracle
def initialize(options, headers)
@options = options
@headers = headers
end
def create_table
create_sql = "create table #{@options[:table_name]} ("
create_sql += @headers.map {|c| "#{c} varchar2(1000)"}.join(',')
create_sql += ");"
open(@options[:table_name] + "/1_create_table.sql", "w") do |f|
f.puts create_sql
end
end
def import_csv
open(@options[:table_name] + "/2_import_csv.sql", "w") do |f|
f.puts "\\copy #{@options[:table_name]}(#{@headers.join(',')}) from '#{@options[:file]}' with encoding 'SJIS' header csv;"
end
end
def drop_table
open(@options[:table_name] + "/3_drop_table.sql", "w") do |f|
f.puts "drop table #{@options[:table_name]};"
end
end
def show_usage
puts <<EOT
Please execute following commands.
# create table to insert
psql -h <host> -d <database> -U <user> < #{@options[:table_name]}/1_create_table.sql
# import csv to table
psql -h <host> -d <database> -U <user> < #{@options[:table_name]}/2_import_csv.sql
# drop table
psql -h <host> -d <database> -U <user> < #{@options[:table_name]}/3_drop_table.sql
EOT
end
end
|
frostdot/net-ldap-auth
|
lib/net/ldap/auth.rb
|
<reponame>frostdot/net-ldap-auth
# coding: utf-8
require 'net/ldap'
module Net
class LDAP
module Auth
module_function
def auth(param)
return false unless param
return false unless param[:host] && param[:host] != ""
return false unless param[:userdn] && param[:userdn] != ""
return false unless param[:password] && param[:password] != ""
authenticate(param[:host], param[:userdn], param[:password])
end
def authenticate(host, userdn, password)
ldap = Net::LDAP.new(
:host => host,
:port => 389,
:auth => {
:method => :simple,
:username => userdn,
:password => password
}
)
ldap.bind
end
end
end
end
|
deivid-rodriguez/activeadmin_addons
|
lib/activeadmin_addons/addons/tag_builder.rb
|
<reponame>deivid-rodriguez/activeadmin_addons
module ActiveAdminAddons
class TagBuilder < CustomBuilder
def render
@enum_attr = if enumerize_attr?
:enumerize
elsif rails_enum_attr?
:enum
end
raise "you need to pass an enumerize or enum attribute" unless @enum_attr
context.status_tag(display_data, class: data)
end
def display_data
@enum_attr == :enumerize ? data.text : data
end
def enumerize_attr?
data.is_a?("Enumerize::Value".constantize)
rescue NameError
false
end
def rails_enum_attr?
defined? Rails && Rails::VERSION::MAJOR == 4 && Rails::VERSION::MINOR >= 1 &&
model.defined_enums[attribute.to_s]
end
end
end
ActiveAdminAddons::TagBuilder.create_view_methods
|
deivid-rodriguez/activeadmin_addons
|
spec/features/tag_builder_spec.rb
|
require 'rails_helper'
describe "Tag Builder", type: :feature do
context "using Enumerize" do
context "changing state value" do
before do
register_index(Invoice) do
tag_column :state
end
create_invoice(state: :approved)
visit admin_invoices_path
end
it "shows set label" do
expect(page).to have_content('Approved')
end
it "shows valid css class" do
expect(page).to have_css('.approved')
end
end
context "passing a block" do
before do
register_show(Invoice) do
tag_row(:state) do
invoice.state
end
end
visit admin_invoice_path(create_invoice)
end
it "localizes the value returned from the block" do
expect(page).to have_content('Pending')
end
it "shows valid css class" do
expect(page).to have_css('.pending')
end
end
context "using a label" do
before do
register_show(Invoice) do
tag_row("custom state", :state)
end
visit admin_invoice_path(create_invoice)
end
it "shows custom label" do
expect(page).to have_content 'Custom State'
end
end
end
context "using Rails Enum" do
context "changing state value" do
before do
register_index(Invoice) do
tag_column :status
end
create_invoice(status: :archived)
visit admin_invoices_path
end
it "shows set value" do
expect(page).to have_css('.archived')
end
end
end
end
|
deivid-rodriguez/activeadmin_addons
|
spec/features/state_builder_spec.rb
|
require 'rails_helper'
describe "State Builder", type: :feature do
context "changing state value" do
before do
register_index(Invoice) do
state_column :aasm_state
end
create_invoice
visit admin_invoices_path
end
it "shows set label" do
expect(page).to have_content('Pending')
end
it "shows valid css class" do
expect(page).to have_css('.pending')
end
end
context "passing a block" do
before do
register_show(Invoice) do
state_row(:aasm_state) do
invoice.state
end
end
visit admin_invoice_path(create_invoice)
end
it "localizes the value returned from the block" do
expect(page).to have_content('Pending')
end
it "shows valid css class" do
expect(page).to have_css('.pending')
end
end
context "using a label" do
before do
register_show(Invoice) do
state_row("custom state", :aasm_state)
end
visit admin_invoice_path(create_invoice)
end
it "shows custom label" do
expect(page).to have_content 'Custom State'
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.