repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
chuckmersereau/api_practice
|
spec/services/web_router_spec.rb
|
require 'rails_helper'
describe WebRouter do
describe '.env' do
it 'returns the current environment' do
expect(described_class.env).to eq('test')
end
end
describe '.host' do
context 'development environment' do
before { expect(WebRouter).to receive(:env).and_return('development') }
it 'returns the expected host' do
expect(described_class.host).to eq('localhost:8080')
end
end
context 'staging environment' do
before { expect(WebRouter).to receive(:env).and_return('staging') }
it 'returns the expected host' do
expect(described_class.host).to eq('stage.mpdx.org')
end
end
%w(production test something).each do |env|
context "#{env} environment" do
before { expect(WebRouter).to receive(:env).and_return(env) }
it 'returns the expected host' do
expect(described_class.host).to eq('mpdx.org')
end
end
end
end
describe '.protocol' do
context 'development environment' do
before { expect(WebRouter).to receive(:env).and_return('development') }
it 'returns the expected protocol' do
expect(described_class.protocol).to eq('http')
end
end
%w(production staging test something).each do |env|
context "#{env} environment" do
before { expect(WebRouter).to receive(:env).and_return(env) }
it 'returns the expected protocol' do
expect(described_class.protocol).to eq('https')
end
end
end
end
describe '.base_url' do
it 'returns the expected url' do
expect(described_class.base_url).to eq('https://mpdx.org')
end
end
describe '.account_list_invite_url' do
let(:invite) { double(account_list: double(id: 'account_list_id'), id: 'invite_id', code: 'invite_code') }
it 'returns the expected url' do
expect(described_class.account_list_invite_url(invite)).to eq('https://mpdx.org/account_lists/account_list_id/accept_invite/invite_id?code=invite_code')
end
end
describe '.integration_preferences_url' do
it 'returns the expected url' do
expect(described_class.integration_preferences_url('asdf')).to eq('https://mpdx.org/preferences/integrations?selectedTab=asdf')
end
end
describe '.notifications_preferences_url' do
it 'returns the expected url' do
expect(described_class.notifications_preferences_url).to eq('https://mpdx.org/preferences/notifications')
end
end
describe '.contact_url' do
let(:contact) { double(id: 'contact_id') }
it 'returns the expected url' do
expect(described_class.contact_url(contact)).to eq('https://mpdx.org/contacts/contact_id')
end
describe 'tab' do
it 'returns the expected url' do
expect(described_class.contact_url(contact, 'donations')).to eq('https://mpdx.org/contacts/contact_id/donations')
end
end
end
describe '.tasks_url' do
it 'returns the expected url' do
expect(described_class.tasks_url).to eq('https://mpdx.org/tasks')
end
end
describe '.person_url' do
let(:person) { double(id: 'person_id', contact: double(id: 'contact_id')) }
it 'returns the expected url' do
expect(described_class.person_url(person)).to eq('https://mpdx.org/contacts/contact_id?personId=person_id')
end
end
describe '.logout_url' do
it 'returns the expected url' do
expect(described_class.logout_url).to eq('https://mpdx.org/logout')
end
end
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/admin/impersonation_controller.rb
|
<filename>app/controllers/api/v2/admin/impersonation_controller.rb
class Api::V2::Admin::ImpersonationController < Api::V2Controller
skip_after_action :verify_authorized
def create
authorize_impersonation
persist_impersonation
render_token
end
private
def persist_impersonation
build_impersonation_log
save_impersonation_log
end
def authorize_impersonation
raise Pundit::NotAuthorizedError,
'must be admin level user to impersonate' unless current_user.admin
end
def save_impersonation_log
@impersonation_log.save
end
def build_impersonation_log
@impersonation_log ||= ::Admin::ImpersonationLog.new(
reason: impersonation_params[:reason],
impersonator: current_user,
impersonated: load_impersonated
)
end
def impersonation_params
params.require(:impersonation)
.permit(:user, :reason)
end
def load_impersonated
@impersonated ||= if UUID_REGEX.match(impersonation_params[:user])
User.find(impersonation_params[:user])
else
find_user_by_email
end
end
def find_user_by_email
user = User.order(:created_at).find_by_email(impersonation_params[:user])
return user if user
raise ActiveRecord::RecordNotFound, "Couldn't find User with email #{impersonation_params[:user]}"
end
def load_token
@token ||= JsonWebToken.encode(
user_id: load_impersonated.id,
exp: 1.hour.from_now.utc.to_i
)
end
def render_token
render json: { data: response_data },
status: 200
end
def response_data
{
attributes: {
json_web_token: load_token
},
type: 'impersonation'
}
end
end
|
chuckmersereau/api_practice
|
db/migrate/20161216004138_add_uuid_to_contact_notes_logs.rb
|
class AddUuidToContactNotesLogs < ActiveRecord::Migration
def change
add_column :contact_notes_logs, :uuid, :uuid, null: false, default: 'uuid_generate_v4()'
add_index :contact_notes_logs, :uuid, unique: true
end
end
|
chuckmersereau/api_practice
|
spec/services/contact/filter/pledge_amount_spec.rb
|
require 'rails_helper'
RSpec.describe Contact::Filter::PledgeAmount do
let!(:user) { create(:user_with_account) }
let!(:account_list) { user.account_lists.order(:created_at).first }
let!(:contact_one) { create(:contact, account_list_id: account_list.id, pledge_amount: 100.00) }
let!(:contact_two) { create(:contact, account_list_id: account_list.id, pledge_amount: 100.00) }
let!(:contact_three) { create(:contact, account_list_id: account_list.id, pledge_amount: 1.00) }
let!(:contact_four) { create(:contact, account_list_id: account_list.id, pledge_amount: nil) }
describe '#config' do
it 'returns expected config' do
options = [{ name: '-- Any --', id: '', placeholder: 'None' },
{ name: 1.0, id: 1.0 },
{ name: 100.0, id: 100.0 }]
expect(described_class.config([account_list])).to include(multiple: true,
name: :pledge_amount,
options: options,
parent: 'Commitment Details',
title: 'Commitment Amount',
type: 'multiselect',
default_selection: '')
end
end
describe '#query' do
let(:contacts) { Contact.all }
context 'no filter params' do
it 'returns nil' do
expect(described_class.query(contacts, {}, nil)).to eq(nil)
expect(described_class.query(contacts, { pledge_amount: {} }, nil)).to eq(nil)
expect(described_class.query(contacts, { pledge_amount: [] }, nil)).to eq(nil)
expect(described_class.query(contacts, { pledge_amount: { wut: '???', hey: 'yo' } }, nil)).to eq(nil)
end
end
context 'filter by amounts' do
it 'returns only contacts with a pledge amount in the filters' do
result = described_class.query(contacts, { pledge_amount: '100.0' }, nil).to_a
expect(result).to match_array [contact_one, contact_two]
result = described_class.query(contacts, { pledge_amount: '1' }, nil).to_a
expect(result).to eq [contact_three]
result = described_class.query(contacts, { pledge_amount: '100.0, 1.0, 200.0' }, nil).to_a
expect(result).to match_array [contact_one, contact_two, contact_three]
end
end
end
end
|
chuckmersereau/api_practice
|
app/models/application_record.rb
|
<reponame>chuckmersereau/api_practice
require 'securerandom'
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
CONFLICT_ERROR_MESSAGE = 'is not equal to the current value in the database'.freeze
# Indicates a record was manually created/updated. Otherwise source usually indicates where it was imported from.
MANUAL_SOURCE = 'MPDX'.freeze
attr_reader :updated_in_db_at
attr_accessor :overwrite
validate :presence_of_updated_in_db_at,
:value_of_updated_in_db_at,
on: :update_from_controller,
unless: :should_overwrite?
def updated_in_db_at=(value)
@updated_in_db_at = value&.is_a?(Time) ? value : Time.parse(value.to_s)
end
# Some resource relationships exposed on the api are not actually Rails associations in our backend (they might just be custom methods).
# We can't preload relationships if they are not actually Rails associations.
# This method is like .preload, but it filters out args that are not proper associations.
def self.preload_valid_associations(*args)
associations = fetch_valid_associations(args)
return preload(*associations) unless associations.empty?
all
end
def self.fetch_valid_associations(*args)
args.flatten.map do |association|
next association if reflections.keys.include?(association.to_s)
fetch_hash_association(association) if association.is_a?(Hash)
end.compact
end
def _client_id=(client_id)
self.id = client_id
end
private
def presence_of_updated_in_db_at
return if updated_at_was.nil? || updated_in_db_at
errors.add(:updated_in_db_at, 'has to be sent in the list of attributes in order to update resource')
end
def value_of_updated_in_db_at
return if updated_at_was.nil? || updated_at_was.to_i == updated_in_db_at.to_i
errors.add(:updated_in_db_at, full_conflict_error_message)
end
def full_conflict_error_message
"#{CONFLICT_ERROR_MESSAGE} (#{updated_at_was&.to_time&.utc&.iso8601})"
end
def should_overwrite?
overwrite.to_s.to_sym == :true
end
def self.fetch_hash_association(association)
association_key = association.keys.first
child_model = reflections.values.detect { |reflection| reflection.name == association_key }
.try(:class_name).try(:constantize)
return unless child_model
{ association_key => child_model.fetch_valid_associations(association.values.first) }
end
private_class_method :fetch_hash_association
end
|
chuckmersereau/api_practice
|
spec/services/account_list/analytics_spec.rb
|
require 'rails_helper'
RSpec.describe AccountList::Analytics, type: :model do
let(:user) { create(:user_with_account) }
let(:account_list) { user.account_lists.order(:created_at).first }
let(:analytics) do
AccountList::Analytics.new(account_list: account_list, start_date: 1.week.ago, end_date: Time.current)
end
def create_task(activity_type:, result: nil, next_action: nil)
create(:task, account_list_id: account_list.id,
activity_type: activity_type,
result: result,
next_action: next_action,
completed: true,
completed_at: 1.day.ago)
# Analytics primarily reports on completed tasks, create incomplete
# tasks so that we can test that they are not counted.
create(:task, account_list_id: account_list.id,
activity_type: activity_type,
result: result,
next_action: next_action,
completed: false,
completed_at: 1.day.ago)
end
before do
# Appointments
create_task(activity_type: 'Appointment', result: 'Completed')
# Contacts
contact = create(:contact, account_list: account_list, status: 'Never Contacted')
contact.contacts_that_referred_me << create(:contact, account_list: account_list)
# Correspondence
create_task(activity_type: 'Pre Call Letter', result: 'Done')
create_task(activity_type: 'Pre Call Letter', result: 'Completed')
create_task(activity_type: 'Reminder Letter', result: 'Done')
create_task(activity_type: 'Support Letter', result: 'Done')
create_task(activity_type: 'Support Letter', result: 'Completed')
create_task(activity_type: 'Thank', result: 'Done')
# Electronic
create_task(activity_type: 'Email', next_action: 'Appointment')
create_task(activity_type: 'Email', result: 'Received')
create_task(activity_type: 'Facebook Message', result: 'Received')
create_task(activity_type: 'Text Message', result: 'Received')
create_task(activity_type: 'Email', result: 'Done')
create_task(activity_type: 'Facebook Message', result: 'Done')
create_task(activity_type: 'Text Message', result: 'Done')
# Phone
create_task(activity_type: 'Call', next_action: 'Appointment')
create_task(activity_type: 'Call', result: 'Attempted')
create_task(activity_type: 'Call', result: 'Completed')
create_task(activity_type: 'Call', result: 'Received')
create_task(activity_type: 'Talk to In Person')
end
describe 'initialize' do
it 'raises error if required arguments are not given' do
expect { AccountList::Analytics.new }
.to raise_error(ArgumentError)
.with_message("account_list can't be blank, start_date can't be blank, end_date can't be blank")
end
it 'initializes successfully' do
expect do
AccountList::Analytics.new(account_list: account_list, start_date: 1.week.ago, end_date: Time.current)
end.to_not raise_error
end
it 'parses string dates as iso8601' do
analytics = AccountList::Analytics.new(account_list: account_list,
start_date: 1.week.ago.iso8601,
end_date: Time.current.iso8601)
expect(analytics.start_date).to be_a Time
expect(analytics.end_date).to be_a Time
expect do
AccountList::Analytics.new(account_list: account_list, start_date: 'hello', end_date: 'world')
end.to raise_error(ArgumentError)
end
it 'accepts time objects' do
analytics = AccountList::Analytics.new(account_list: account_list,
start_date: 1.week.ago,
end_date: Time.current)
expect(analytics.start_date).to be_a Time
expect(analytics.end_date).to be_a Time
end
end
describe '#appointments' do
subject { analytics.appointments }
it 'returns count of completed appointment tasks' do
expect(subject).to eq(completed: 1)
end
end
describe '#contacts' do
subject { analytics.contacts }
it 'returns counts of contacts' do
expect(subject).to eq(active: 1, referrals: 1, referrals_on_hand: 1)
end
end
describe '#correspondence' do
subject { analytics.correspondence }
it 'returns counts of completed correspondence tasks' do
expect(subject).to eq(precall: 2, reminders: 1, support_letters: 2, thank_yous: 1)
end
end
describe '#electronic' do
subject { analytics.electronic }
it 'returns counts of electronic related tasks' do
expect(subject).to eq(appointments: 1, received: 3, sent: 4)
end
end
describe '#email' do
subject { analytics.email }
it 'returns counts of email related tasks' do
expect(subject).to eq(received: 1, sent: 2)
end
end
describe '#facebook' do
subject { analytics.facebook }
it 'returns counts of facebook related tasks' do
expect(subject).to eq(received: 1, sent: 1)
end
end
describe '#phone' do
subject { analytics.phone }
it 'returns counts of phone related tasks' do
expect(subject).to eq(appointments: 1, attempted: 1, completed: 2, received: 1, talktoinperson: 1)
end
end
describe '#text_message' do
subject { analytics.text_message }
it 'returns counts of text_message related tasks' do
expect(subject).to eq(received: 1, sent: 1)
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20121223165958_create_donor_account_people.rb
|
class CreateDonorAccountPeople < ActiveRecord::Migration
def change
create_table :donor_account_people do |t|
t.belongs_to :donor_account
t.belongs_to :person
t.timestamps null: false
end
add_index :donor_account_people, :donor_account_id
add_index :donor_account_people, :person_id
end
end
|
chuckmersereau/api_practice
|
spec/services/task/filter/date_range_spec.rb
|
require 'rails_helper'
RSpec.describe Task::Filter::DateRange do
let!(:user) { create(:user_with_account) }
let!(:account_list) { user.account_lists.order(:created_at).first }
let!(:task_last_week) { create(:task, account_list: account_list, completed: true, completed_at: 1.week.ago) }
let!(:task_last_month) { create(:task, account_list: account_list, completed: true, completed_at: 1.month.ago) }
let!(:task_last_year) { create(:task, account_list: account_list, completed: true, completed_at: 1.year.ago) }
let!(:task_last_two_years) { create(:task, account_list: account_list, completed: true, completed_at: 2.years.ago) }
let!(:task_overdue) { create(:task, account_list: account_list, completed: false, start_at: 1.day.ago) }
let!(:task_today) { create(:task, account_list: account_list, completed: false, start_at: 1.minute.from_now) }
let!(:task_tomorrow) { create(:task, account_list: account_list, completed: false, start_at: 1.day.from_now) }
let!(:task_next_week) { create(:task, account_list: account_list, completed: false, start_at: 1.week.from_now) }
let!(:task_no_date) { create(:task, account_list: account_list, start_at: nil) }
describe '#query' do
let(:tasks) { account_list.tasks }
context 'no filter params' do
it 'returns nil' do
expect(described_class.query(tasks, {}, nil)).to eq(nil)
expect(described_class.query(tasks, { date_range: {} }, nil)).to eq(nil)
expect(described_class.query(tasks, { date_range: [] }, nil)).to eq(nil)
expect(described_class.query(tasks, { date_range: '' }, nil)).to eq(nil)
end
end
context 'filter by date_range' do
it 'filters where task completed last_week' do
expect(described_class.query(tasks, { date_range: 'last_week' }, nil).to_a).to eq([task_last_week])
end
it 'filters where task completed last_month' do
expect(described_class.query(tasks, { date_range: 'last_month' }, nil).to_a).to eq([task_last_month])
end
it 'filters where task completed last_year' do
expect(described_class.query(tasks, { date_range: 'last_year' }, nil).to_a).to eq([task_last_year])
end
it 'filters where task completed last_two_years' do
expect(described_class.query(tasks, { date_range: 'last_two_years' }, nil).to_a).to eq([task_last_two_years])
end
it 'filters where task start_at overdue' do
expect(described_class.query(tasks, { date_range: 'overdue' }, nil).to_a).to eq([task_overdue])
end
it 'filters where task start_at today' do
expect(described_class.query(tasks, { date_range: 'today' }, nil).to_a).to eq([task_today])
end
it 'filters where task start_at tomorrow' do
expect(described_class.query(tasks, { date_range: 'tomorrow' }, nil).to_a).to eq([task_tomorrow])
end
it 'filters where task start_at future' do
future_tasks = [task_today, task_tomorrow, task_next_week]
expect(described_class.query(tasks, { date_range: 'future' }, nil).to_a).to match_array(future_tasks)
end
it 'filters where task start_at upcoming' do
upcoming_tasks = [task_tomorrow, task_next_week]
expect(described_class.query(tasks, { date_range: 'upcoming' }, nil).to_a).to match_array(upcoming_tasks)
end
it 'filters where task start_at is nil' do
expect(described_class.query(tasks, { date_range: 'no_date' }, nil).to_a).to eq([task_no_date])
end
end
end
end
|
chuckmersereau/api_practice
|
db/migrate/20170810174948_create_duplicate_record_pairs.rb
|
class CreateDuplicateRecordPairs < ActiveRecord::Migration
def change
create_table :duplicate_record_pairs do |t|
t.uuid :uuid, null: false, default: 'uuid_generate_v4()'
t.integer :account_list_id, null: false
t.integer :record_one_id, null: false
t.string :record_one_type, null: false
t.integer :record_two_id, null: false
t.string :record_two_type, null: false
t.string :reason, null: false
t.boolean :ignore, default: false, null: false
t.timestamps null: false
end
add_index :duplicate_record_pairs, :uuid, unique: true
add_index :duplicate_record_pairs, [:record_one_type, :record_two_type, :record_one_id, :record_two_id], unique: true, name: 'index_dup_record_pairs_on_record_types_and_ids'
add_index :duplicate_record_pairs, :account_list_id
add_index :duplicate_record_pairs, [:record_one_type, :record_one_id], name: 'index_dup_record_pairs_on_record_one_type_and_record_one_id'
add_index :duplicate_record_pairs, [:record_two_type, :record_two_id], name: 'index_dup_record_pairs_on_record_two_type_and_record_two_id'
end
end
|
chuckmersereau/api_practice
|
app/services/contact/filter/pledge_amount_increased_range.rb
|
class Contact::Filter::PledgeAmountIncreasedRange < Contact::Filter::Base
attr_accessor :scope, :filters
def execute_query(scope, filters)
@scope = scope
@filters = filters
scope.where(id: contact_ids_where_pledge_amount_changed)
end
def valid_filters?(filters)
date_range?(filters[:pledge_amount_increased_range])
end
private
def contact_ids_where_pledge_amount_changed
log_monthly_amount = 'MAX(coalesce(partner_status_logs.pledge_amount, 0.0) / coalesce(partner_status_logs.pledge_frequency, 1.0))'
contact_monthly_amount = 'coalesce(contacts.pledge_amount, 0.0) / coalesce(contacts.pledge_frequency, 1.0)'
PartnerStatusLog.where(contact_id: scope.pluck(:id))
.where(recorded_on: filters[:pledge_amount_increased_range])
.joins(:contact)
.group('contact_id, contacts.pledge_amount, contacts.pledge_frequency')
.having("#{log_monthly_amount} < #{contact_monthly_amount}")
.pluck(:contact_id)
end
end
|
chuckmersereau/api_practice
|
app/serializers/pledge_serializer.rb
|
class PledgeSerializer < ApplicationSerializer
attributes :amount,
:expected_date,
:status
belongs_to :account_list
belongs_to :contact
has_many :donations
end
|
chuckmersereau/api_practice
|
spec/serializers/appeal_serializer_spec.rb
|
<filename>spec/serializers/appeal_serializer_spec.rb
require 'rails_helper'
RSpec.describe AppealSerializer do
let!(:appeal) { create(:appeal) }
let!(:donation_one) { create(:donation, currency: 'CAD').tap { |donation| appeal.donations << donation } }
let!(:donation_two) { create(:donation, currency: 'ZAR').tap { |donation| appeal.donations << donation } }
let(:serializer) { AppealSerializer.new(appeal) }
let(:parsed_json_response) { JSON.parse(serializer.to_json) }
describe '#currencies' do
it 'returns all currencies from the donations' do
expect(parsed_json_response['currencies']).to match_array(%w(CAD ZAR))
end
end
describe '#total_currency' do
it 'returns the account list salary currency' do
expect(parsed_json_response['total_currency']).to eq(appeal.account_list.salary_currency)
end
end
end
|
chuckmersereau/api_practice
|
app/controllers/api/v2/reports/sessions_controller.rb
|
class Api::V2::Reports::SessionsController < Api::V2Controller
def show
@sessions = Session.where(:user => params[:id])
authorize(@sessions)
render json: @sessions
end
def create
@session = Session.new(session_params)
@session.save
authorize(@session)
render json: @session
end
private
def session_params
params.require(:session).permit(:user, :sid)
end
end
|
chuckmersereau/api_practice
|
db/migrate/20140204165556_add_index_to_notifications.rb
|
<gh_stars>0
class AddIndexToNotifications < ActiveRecord::Migration
def change
add_index :notifications, :donation_id
end
end
|
chuckmersereau/api_practice
|
spec/support/shared_controller_examples/filtering_examples.rb
|
<filename>spec/support/shared_controller_examples/filtering_examples.rb
RSpec.shared_examples 'filtering examples' do |options|
it 'reduces the count of items returned when a filter is used' do
if defined?(filter_params)
api_login(user)
get options[:action], parent_param_if_needed
expect do
get options[:action], parent_param_if_needed.merge(filter: filter_params)
end.to change { JSON.parse(response.body)['data'].length }.by(-1)
end
end
it 'returns the id in the meta tag when passed as a filter' do
if options[:action] == :index && described_class.new.send(:permitted_filters).include?(:account_list_id)
api_login(user)
get :index, parent_param_if_needed.merge(filter: { account_list_id: account_list.id })
expect(response.status).to eq(200), invalid_status_detail
expect(JSON.parse(response.body)['meta']['filter']['account_list_id']).to eq(account_list.id)
end
end
it 'returns meta for given filter' do
if defined?(filterer_class)
api_login(user)
# Use permitted_filters here instead of filterer_class.filter_params
filterer_class.filter_params.collect(&:to_s).each do |filter|
filter_value = ''
filter_value = Date.current if CastedValueValidator::DATE_FIELD_ENDINGS.any? { |ending| filter.to_s.end_with?(ending) }
get :index, filter: { filter => filter_value }
expect(response.status).to eq(200), invalid_status_detail
expect(JSON.parse(response.body)['meta']['filter'][filter]).to eq(filter_value.to_s)
end
end
end
end
|
chuckmersereau/api_practice
|
lib/json_api_service/relationships_object.rb
|
require 'forwardable'
require 'json_api_service/data_object'
require 'json_api_service/data_object_collection'
require 'json_api_service/null_data_object'
module JsonApiService
class RelationshipsObject < BaseObject
extend Forwardable
def_delegators :relationships, :[]
def_delegators :data, :empty?
attr_reader :relationships
def to_h
relationships.each_with_object({}) do |(relationship_type, object), hash|
hash[relationship_type] = {
data: to_h_data_from_object(object)
}
end
end
def validate_against_store
relationships.values.each(&:validate_against_store)
end
private
def after_initialize
parse_relationships
end
def parse_object_from_relationship_data(relationship_data, args)
case relationship_data
when Array
DataObjectCollection.new(relationship_data, args)
when Hash
DataObject.new(relationship_data, args)
else
NullDataObject.new
end
end
def parse_relationships
@relationships = data.each_with_object({}) do |(relationship_type, hash_with_data), hash|
relationship_data = hash_with_data.dig(:data)
args = { parent: self, store: store }
parsed_object = parse_object_from_relationship_data(relationship_data, args)
hash[relationship_type] = parsed_object
end
end
def to_h_data_from_object(object)
case object
when DataObject
object.to_h
when DataObjectCollection
object.to_a
end
end
end
end
|
chuckmersereau/api_practice
|
spec/models/master_company_spec.rb
|
<reponame>chuckmersereau/api_practice
require 'rails_helper'
describe MasterCompany do
it 'should find an existing master company' do
company = FactoryBot.create(:company)
expect do
expect(MasterCompany.find_or_create_for_company(FactoryBot.build(:company)))
.to eq(company.master_company)
end.to_not change(MasterCompany, :count)
end
it 'should create a new master company' do
expect do
MasterCompany.find_or_create_for_company(FactoryBot.build(:company))
end.to change(MasterCompany, :count)
end
end
|
chuckmersereau/api_practice
|
dev/util/sql_export_util.rb
|
<reponame>chuckmersereau/api_practice<gh_stars>0
# Allows exporting of the core data of an acount list to SQL for local
# debugging of user issues.
def save_account_list_sql_to_s3(account_list)
filename = "account_list_#{account_list.id}_at_#{Time.now.to_i}.sql"
upload_to_s3(filename, account_list_sql(account_list))
end
def upload_to_s3(filename, body)
conn = Fog::Storage.new(provider: 'AWS',
aws_access_key_id: ENV.fetch('AWS_ACCESS_KEY_ID'),
aws_secret_access_key: ENV.fetch('AWS_SECRET_ACCESS_KEY'))
dir = conn.directories.get(ENV.fetch('AWS_BUCKET'))
path = "debug_exports/#{filename}"
file = dir.files.new(key: path, body: body)
file.save
puts "Saved in #{ENV.fetch('AWS_BUCKET')} bucket at #{path}"
end
def account_list_sql(account_list)
sql = []
sql << model_insert_sql(account_list)
[
account_list.contacts,
account_list.people,
account_list.addresses,
ContactPerson.where(contact: account_list.contacts),
PhoneNumber.where(person: account_list.people),
EmailAddress.where(person: account_list.people)
].each do |relation|
sql += relation_insert_sql(relation)
end
sql.join("\n")
end
def relation_insert_sql(relation)
relation.uniq.map(&method(:model_insert_sql))
end
def model_insert_sql(model)
quoted_columns = []
quoted_values = []
attributes_with_values =
model.send(:arel_attributes_with_values_for_create, model.attribute_names)
attributes_with_values.each_pair do |key, value|
quoted_columns << ActiveRecord::Base.connection.quote_column_name(key.name)
quoted_values << ActiveRecord::Base.connection.quote(value)
end
"INSERT INTO #{model.class.quoted_table_name} (#{quoted_columns.join(', ')}) VALUES (#{quoted_values.join(', ')});\n"
end
|
chuckmersereau/api_practice
|
spec/serializers/error_serializer_spec.rb
|
require 'rails_helper'
RSpec.describe ErrorSerializer, type: :serializer do
let(:resource) { MockResource.new }
let(:title) { 'Not Found' }
let(:detail) { "Couldn't find resource at /api/v2/google" }
let(:status) { 400 }
let(:error_hash) do
{
name: "can't be blank",
email: 'must be unique'
}
end
describe '#initialize' do
it 'must initialize with a status' do
expect { ErrorSerializer.new(status: nil) }.to raise_error ArgumentError
end
it 'must initialize with either a title or a resource or a hash' do
invalid_args = {
status: status,
hash: nil,
resource: nil,
title: nil
}
expect { ErrorSerializer.new(invalid_args) }
.to raise_error ArgumentError
expect { ErrorSerializer.new(resource: resource, status: status) }
.not_to raise_error
expect { ErrorSerializer.new(title: title, status: status) }
.not_to raise_error
expect { ErrorSerializer.new(hash: error_hash, status: status) }
.not_to raise_error
end
end
describe '#as_json' do
it 'returns a Hash' do
serializer = ErrorSerializer.new(status: 400, resource: resource)
expect(serializer.as_json).to be_a Hash
end
context 'with a resource' do
it 'will correctly generate the json for the errors on the resource' do
expected_json_hash = {
errors: [
{
status: 400,
source: { pointer: '/data/attributes/name' },
title: 'must be in ALL CAPS',
detail: 'Name must be in ALL CAPS'
},
{
status: 400,
source: { pointer: '/data/attributes/name' },
title: 'must contain a ?',
detail: 'Name must contain a ?'
},
{
status: 400,
source: { pointer: '/data/attributes/email' },
title: 'has already been taken',
detail: 'Email has already been taken'
},
{
status: 400,
source: { pointer: '/data/attributes/updated_in_db_at' },
title: 'is not equal to the current value in the database',
detail: 'Updated in db at is not equal to the current value in the database',
meta: {
updated_in_db_at: resource.updated_at.utc.iso8601
}
}
]
}.as_json
serializer = ErrorSerializer.new(status: 400, resource: resource)
expect(serializer.as_json).to eq expected_json_hash
end
end
context 'with a resource with a 409 conflict' do
it 'will correctly generate the json for a 409 conflict' do
expected_json_hash = {
errors: [
{
status: 409,
source: { pointer: '/data/attributes/name' },
title: 'must be in ALL CAPS',
detail: 'Name must be in ALL CAPS'
},
{
status: 409,
source: { pointer: '/data/attributes/name' },
title: 'must contain a ?',
detail: 'Name must contain a ?'
},
{
status: 409,
source: { pointer: '/data/attributes/email' },
title: 'has already been taken',
detail: 'Email has already been taken'
},
{
status: 409,
source: { pointer: '/data/attributes/updated_in_db_at' },
title: 'is not equal to the current value in the database',
detail: 'Updated in db at is not equal to the current value in the database',
meta: {
updated_in_db_at: resource.updated_at.utc.iso8601
}
}
]
}.as_json
serializer = ErrorSerializer.new(status: 409, resource: resource)
expect(serializer.as_json).to eq expected_json_hash
end
end
context 'with a title' do
it 'will correctly generate the json for the error title' do
expected_json_hash = {
errors: [
{
status: 404,
title: 'Not Found',
detail: "Couldn't find resource at /api/v2/google"
}
]
}.as_json
arguments = {
status: 404,
title: title,
detail: detail
}
serializer = ErrorSerializer.new(arguments)
expect(serializer.as_json).to eq expected_json_hash
end
end
context 'with a hash of errors' do
it 'will correctly generate the json for the errors from the hash' do
expected_json_hash = {
errors: [
{
status: 400,
source: { pointer: '/data/attributes/name' },
title: "can't be blank",
detail: "Name can't be blank"
},
{
status: 400,
source: { pointer: '/data/attributes/email' },
title: 'must be unique',
detail: 'Email must be unique'
}
]
}.as_json
serializer = ErrorSerializer.new(status: 400, hash: error_hash)
expect(serializer.as_json).to eq expected_json_hash
end
end
end
class MockResource
extend ActiveModel::Translation
def errors
@errors ||= build_errors
end
def updated_at
@updated_at ||= 1.hour.ago
end
private
def build_errors
ActiveModel::Errors.new(self).tap do |errors|
errors.add(:name, 'must be in ALL CAPS')
errors.add(:name, 'must contain a ?')
errors.add(:email, 'has already been taken')
errors.add(:updated_in_db_at, 'is not equal to the current value in the database')
end
end
end
end
|
chuckmersereau/api_practice
|
spec/factories/designation_profile_accounts.rb
|
FactoryBot.define do
factory :designation_profile_account do
designation_profile nil
designation_account nil
end
end
|
chuckmersereau/api_practice
|
spec/factories/background_batch_requests.rb
|
<reponame>chuckmersereau/api_practice
FactoryBot.define do
factory :background_batch_request, class: 'BackgroundBatch::Request' do
background_batch
path 'api/v2/user'
end
end
|
squiggle-lang/squiggle-lang.org
|
_plugins/table_of_contents.rb
|
module TableOfContents
class Generator < Jekyll::Generator
# Chapter files are stored in /tutorial/chapter/NUM/index.md
SEC_REGEXP = %r{/tutorial/chapter/(\d+)}
def generate(site)
pairs = site
.pages
.select {|page| page.basename == "index" }
.map {|page| [page, page.dir.match(SEC_REGEXP)] }
.select {|pair| pair[1] }
.map {|pair|
page, match = pair
chapter = match[1].to_i
toc_data = {
"title" => page.data["title"],
"chapter" => chapter,
}
[page, toc_data]
}
.sort_by {|pair| pair[1]["chapter"] }
# Grab just the chapter array for use later.
toc = pairs.map {|p| p[1] }
# Find the page with the table of contents in it and inject the
# chapters array as page data.
site
.pages
.select {|p|
p.dir.start_with?("/tutorial") &&
p.basename == "index"
}
.each {|p| p.data["toc"] = toc }
# Inject various metadata used for chapters to render correctly.
pairs.each {|pair|
page, n = pair
i = toc.index(n)
n_prev = _chapter_plus_n(toc, i, -1)
n_next = _chapter_plus_n(toc, i, +1)
chapter = toc[i]["chapter"]
old_title = page.data["title"]
new_title = format("%d. %s", chapter, old_title)
page.data.merge!({
"layout" => "chapter",
"title" => new_title,
"chapter" => chapter.to_s,
"next" => n_next,
"previous" => n_prev,
})
}
end
# Tries to return the next/previous chapter or nil.
def _chapter_plus_n(toc, i, mod)
return nil if i == nil
j = i + mod
return nil if j < 0 || j >= toc.length
toc[j]["chapter"]
end
end
end
|
squiggle-lang/squiggle-lang.org
|
_plugins/rouge_add_squiggle.rb
|
<filename>_plugins/rouge_add_squiggle.rb
require 'rouge'
# -*- coding: utf-8 -*- #
module Rouge
module Lexers
class Squiggle < RegexLexer
title "Squiggle"
desc "A strict, functional, compile-to-JS language"
tag 'squiggle'
filenames '*.sqg'
mimetypes 'text/x-squiggle'
state :root do
# comments
rule(/#.*$/, Comment::Single)
rule(/\s+/m, Text)
rule(/[0-9][0-9_]*\.[0-9][0-9_]*/, Num::Float)
rule(/[0-9][0-9_]*/, Num::Integer)
rule(/\bInfinity\b/, Num)
rule(/\bNaN\b/, Num)
rule(/\b(?:export|try|throw|error|fn|if|then|else|elseif|match|case|let|def|in|await|require|do|end)\b/, Keyword)
rule(/"(?:\\\\|\\"|[^"])*"/, Str)
rule(/\b(?:true|false|undefined|null|global)\b/, Name::Constant)
rule(/(?:\+\+|~|\+|-|\*|\/|=>|<=|>=|>|<|==|!=|=|&)/, Operator)
rule(/\b(?:and|or|is|not|has)\b/, Operator)
rule(/[,\.:{}\[\]()@]+/, Punctuation)
rule(/[a-zA-Z_][a-zA-Z0-9_]*/, Name::Variable)
end
end
end
end
|
mezbahalam/peatio
|
app/models/concerns/fund_sourceable.rb
|
module FundSourceable
extend ActiveSupport::Concern
included do
attr_accessor :fund_source_id
before_validation :set_fund_source_attributes, on: :create
validates :fund_source_id, presence: true, on: :create
end
def set_fund_source_attributes
if fs = FundSource.find_by(id: fund_source_id)
self.fund_extra = fs.extra
self.fund_uid = fs.uid.strip
end
end
end
|
jbaker48/oxidized
|
lib/oxidized/hook/exec.rb
|
class Exec < Oxidized::Hook
include Process
def initialize
super
@timeout = 60
@async = false
end
def validate_cfg!
# Syntax check
if cfg.has_key? "timeout"
@timeout = cfg.timeout
raise "invalid timeout value" unless @timeout.is_a?(Integer) &&
@timeout > 0
end
if cfg.has_key? "async"
@async = !!cfg.async
end
if cfg.has_key? "cmd"
@cmd = cfg.cmd
raise "invalid cmd value" unless @cmd.is_a?(String) || @cmd.is_a?(Array)
end
rescue RuntimeError => e
raise ArgumentError,
"#{self.class.name}: configuration invalid: #{e.message}"
end
def run_hook ctx
env = make_env ctx
log "Execute: #{@cmd.inspect}", :debug
th = Thread.new do
begin
run_cmd! env
rescue => e
raise e unless @async
end
end
th.join unless @async
end
def run_cmd! env
pid, status = nil, nil
Timeout.timeout(@timeout) do
pid = spawn env, @cmd , :unsetenv_others => true
pid, status = wait2 pid
unless status.exitstatus.zero?
msg = "#{@cmd.inspect} failed with exit value #{status.exitstatus}"
log msg, :error
raise msg
end
end
rescue TimeoutError
kill "TERM", pid
msg = "#{@cmd} timed out"
log msg, :error
raise TimeoutError, msg
end
def make_env ctx
env = {
"OX_EVENT" => ctx.event.to_s
}
if ctx.node
env.merge!(
"OX_NODE_NAME" => ctx.node.name.to_s,
"OX_NODE_FROM" => ctx.node.from.to_s,
"OX_NODE_MSG" => ctx.node.msg.to_s,
"OX_NODE_GROUP" => ctx.node.group.to_s,
"OX_EVENT" => ctx.event.to_s,
"OX_REPO_COMMITREF" => ctx.commitref.to_s,
"OX_REPO_NAME" => ctx.node.repo.to_s,
)
end
if ctx.job
env.merge!(
"OX_JOB_STATUS" => ctx.job.status.to_s,
"OX_JOB_TIME" => ctx.job.time.to_s,
)
end
env
end
end
|
jbaker48/oxidized
|
lib/oxidized/model/airos.rb
|
class Airos < Oxidized::Model
# Ubiquiti AirOS circa 5.x
prompt /^[^#]+# /
cmd 'cat /etc/board.info' do |cfg|
cfg.split("\n").map { |line| "# #{line}" }.join("\n") + "\n"
end
cmd 'sort /tmp/system.cfg'
cmd :secret do |cfg|
cfg.gsub! /^(users\.\d+\.password|snmp\.community)=.+/, "# \\1=<hidden>"
cfg
end
cfg :ssh do
exec true
end
end
|
jbaker48/oxidized
|
lib/oxidized/source/csv.rb
|
<gh_stars>0
module Oxidized
class CSV < Source
def initialize
@cfg = Oxidized.config.source.csv
super
end
def setup
if @cfg.empty?
Oxidized.asetus.user.source.csv.file = File.join(Config::Root, 'router.db')
Oxidized.asetus.user.source.csv.delimiter = /:/
Oxidized.asetus.user.source.csv.map.name = 0
Oxidized.asetus.user.source.csv.map.model = 1
Oxidized.asetus.save :user
raise NoConfig, 'no source csv config, edit ~/.config/oxidized/config'
end
end
def load
nodes = []
open(File.expand_path @cfg.file).each_line do |line|
next if line.match(/^\s*#/)
data = line.chomp.split(@cfg.delimiter, -1)
next if data.empty?
# map node parameters
keys = {}
@cfg.map.each do |key, position|
keys[key.to_sym] = node_var_interpolate data[position]
end
keys[:model] = map_model keys[:model] if keys.key? :model
# map node specific vars
vars = {}
@cfg.vars_map.each do |key, position|
vars[key.to_sym] = node_var_interpolate data[position]
end
keys[:vars] = vars unless vars.empty?
nodes << keys
end
nodes
end
end
end
|
jbaker48/oxidized
|
lib/oxidized/model/nxos.rb
|
class NXOS < Oxidized::Model
prompt /^(\r?[\w.@_()-]+[#]\s?)$/
comment '! '
cmd 'show version' do |cfg|
cfg = cfg.each_line.take_while { |line| not line.match(/uptime/i) }
comment cfg.join ""
end
cmd 'show inventory' do |cfg|
comment cfg
end
cmd 'show running-config' do |cfg|
cfg.gsub! /^!Time:[^\n]*\n/, ''
end
cfg :ssh do
post_login 'terminal length 0'
pre_logout 'exit'
end
end
|
jbaker48/oxidized
|
lib/oxidized/source/http.rb
|
module Oxidized
class HTTP < Source
def initialize
@cfg = Oxidized.config.source.http
super
end
def setup
if @cfg.url.empty?
raise NoConfig, 'no source http url config, edit ~/.config/oxidized/config'
end
end
require "net/http"
require "uri"
require "json"
def load
nodes = []
uri = URI.parse(@cfg.url)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true if uri.scheme == 'https'
http.verify_mode = OpenSSL::SSL::VERIFY_NONE unless @cfg.secure
# map headers
headers = {}
@cfg.headers.each do |header, value|
headers[header] = value
end
request = Net::HTTP::Get.new(uri.request_uri, headers)
if (@cfg.user && @cfg.pass)
request.basic_auth(@cfg.user,@cfg.pass)
end
response = http.request(request)
data = JSON.parse(response.body)
data.each do |line|
next if line.empty?
# map node parameters
keys = {}
@cfg.map.each do |key, position|
keys[key.to_sym] = node_var_interpolate line[position]
end
keys[:model] = map_model keys[:model] if keys.key? :model
# map node specific vars
vars = {}
@cfg.vars_map.each do |key, position|
vars[key.to_sym] = node_var_interpolate line[position]
end
keys[:vars] = vars unless vars.empty?
nodes << keys
end
nodes
end
end
end
|
jbaker48/oxidized
|
lib/oxidized/model/fabricos.rb
|
class FabricOS < Oxidized::Model
# Brocade Fabric OS model #
## FIXME: Only ssh exec mode support, no telnet, no ssh screenscraping
prompt /^([\w]+:+[\w]+[>]\s)$/
comment '# '
cmd 'chassisShow' do |cfg|
comment cfg
end
cmd 'configShow -all' do |cfg|
cfg
end
cfg :ssh do
exec true # don't run shell, run each command in exec channel
end
end
|
toreta/second
|
lib/time_second.rb
|
# frozen_string_literal: true
# Make it easy to handle numeric value as seconds.
class TimeSecond < Numeric
VERSION = '0.1.0'
include Comparable
# Parse 'HH:MM:SS' format string and return its object
#
# @param [String] str 'HH:MM:SS' or 'HH:MM'
#
# @return [TimeSecond]
def self.parse(str)
unless str.match(/\A\d{1,2}:\d{2}(?:\:\d{2})?\z/)
raise ArgumentError, 'Invalid string format'
end
h, m, s = str.split(':')
new(h.to_i * 60 * 60 + m.to_i * 60 + s.to_i)
end
def initialize(time) # :nodoc:
@time = time
end
# Returns integer value of seconds
#
# @return [Integer] seconds
def to_i
@time.to_int
end
# Returns float value of seconds
#
# @return [Float] seconds
def to_f
@time.to_f
end
# Return hour
#
# @return [Integer] Hour (0 ~ )
def hour
@time.to_i / 60 / 60
end
# Return minute
#
# @return [Integer] Minute (0 ~ 59)
def minute
@time.to_i / 60 % 60
end
# Return second
#
# @return [Integer] TimeSecond (0 ~ 59)
def second
@time.to_i % 60
end
# Return 'HH:MM:SS' format string
#
# @param [String] sep Seperator string. Default is ':'.
#
# @return [String] 'HH:MM:SS'
def hms(sep = ':')
"%02d#{sep}%02d#{sep}%02d" % [hour, minute, second]
end
# Return 'HH:MM' format string
#
# @param [String] sep Seperator string. Default is ':'.
#
# @return [String] 'HH:MM'
def hm(sep = ':')
"%02d#{sep}%02d" % [hour, minute]
end
# Compares one TimeSecond and another or a Numeric to this TimeSecond.
def <=>(other)
@time <=> other
end
# Returns true if other is with the same time.
def ==(other)
@time.to_f == other.to_f
end
# Adds another TimeSecond or Numeric to this TimeSecond.
def +(other)
r, l = @time.coerce(other)
self.class.new(l + r)
end
# Subtracts another TimeSecond or Numeric from this TimeSecond.
def -(other)
r, l = @time.coerce(other)
self.class.new(l - r)
end
# Multiple self by a Numeric and returns a new TimeSecond.
def *(other)
r, l = @time.coerce(other)
self.class.new(l * r)
end
# Divides self by a Numeric and returns a new TimeSecond.
def /(other)
r, l = @time.coerce(other)
self.class.new(l / r)
end
# Returns the modulo of this by another TimeSecond or Numeric.
def %(other)
r, l = @time.coerce(other)
self.class.new(l % r)
end
end
|
toreta/second
|
test/time_second_test.rb
|
require 'test_helper'
class TimeSecondTest < Minitest::Test
def test_that_it_has_a_version_number
refute_nil ::TimeSecond::VERSION
end
T1 = 2 * 60 * 60 + 1 * 60 + 39
T2 = 2 * 60 * 60 + 1 * 60 + 41.258
def setup
@t1 = TimeSecond.new(T1)
@t2 = TimeSecond.new(T2)
end
def test_hour
assert_equal @t1.hour, 2
assert_equal @t2.hour, 2
end
def test_minute
assert_equal @t1.minute, 1
assert_equal @t2.minute, 1
end
def test_second
assert_equal @t1.second, 39
assert_equal @t2.second, 41
end
def test_hms
assert_equal @t1.hms, '02:01:39'
assert_equal @t2.hms, '02:01:41'
end
def test_hm
assert_equal @t1.hm, '02:01'
assert_equal @t2.hm, '02:01'
end
def test_parse
assert_instance_of TimeSecond, TimeSecond.parse('02:01:39')
assert_equal @t1.hour, 2
assert_equal @t1.minute, 1
assert_equal @t1.second, 39
end
def test_parse_with_invalid_format
assert_raises ArgumentError do
TimeSecond.parse('020139')
end
end
def test_compares
assert @t1 < @t2
end
def test_equality
assert @t1 == T1
assert @t1 == TimeSecond.new(T1)
assert @t1 == Float(T1)
assert @t1 != T2
assert @t1 != @t2
end
def test_add
assert_instance_of TimeSecond, TimeSecond.new(7) + 3
assert_equal TimeSecond.new(7) + TimeSecond.new(3), TimeSecond.new(10)
assert_equal TimeSecond.new(7.1) + 3, TimeSecond.new(10.1)
end
def test_subtract
assert_instance_of TimeSecond, TimeSecond.new(7) - 3
assert_equal TimeSecond.new(7) - TimeSecond.new(3), TimeSecond.new(4)
assert_equal TimeSecond.new(7.1) - 3, TimeSecond.new(4.1)
end
def test_multiple
assert_instance_of TimeSecond, TimeSecond.new(7) * 3
assert_equal TimeSecond.new(7) * 3, TimeSecond.new(21)
end
def test_divide
assert_instance_of TimeSecond, TimeSecond.new(7) / 3
assert_equal TimeSecond.new(7) / 3, TimeSecond.new(7 / 3)
end
def test_modulo
assert_instance_of TimeSecond, TimeSecond.new(7) % 3
assert_equal TimeSecond.new(7) % 3, 1
end
end
|
piotrj/dj_one
|
test/test_helper.rb
|
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'dj_one'
require "yaml"
require "sqlite3"
require 'minitest/autorun'
require "dj_one/templates/install_dj_one_migration"
def connect_active_record
adapter = "sqlite"
config_file = File.expand_path("config/database.yml", File.dirname(__FILE__))
puts "DB: #{adapter}"
puts "Config file: #{config_file}"
config = YAML.load_file(config_file)[adapter]
puts config.inspect
ActiveRecord::Base.logger = ActiveSupport::Logger.new("debug.log", 0, 100 * 1024 * 1024)
ActiveRecord::Base.establish_connection config
end
def load_db_schema
ActiveRecord::Schema.define do
create_table :delayed_jobs, force: true do |table|
table.integer :priority, default: 0, null: false
table.integer :attempts, default: 0, null: false
table.text :handler, null: false
table.text :last_error
table.datetime :run_at
table.datetime :locked_at
table.datetime :failed_at
table.string :locked_by
table.string :queue
table.timestamps null: true
end
add_index :delayed_jobs, [:priority, :run_at], name: "delayed_jobs_priority"
InstallDjOne.up
end
end
def install_plugin
end
connect_active_record
load_db_schema
install_plugin
|
piotrj/dj_one
|
test/dj_plugin_test.rb
|
require 'test_helper'
class OtherPlugin < Delayed::Plugin
cattr_writer :callbacks_run
callbacks do |lifecycle|
lifecycle.around(:enqueue, &method(:handle_enqueue))
lifecycle.around(:perform, &method(:handle_perform))
lifecycle.around(:failure, &method(:handle_failure))
end
def self.handle_enqueue(job, &block)
self.callbacks_run << :enqueue
block.call(job)
end
def self.handle_perform(worker, job, &block)
self.callbacks_run << :perform
block.call(worker, job)
end
def self.handle_failure(worker, job, &block)
self.callbacks_run << :failure
block.call(worker, job)
end
def self.callbacks_run
@@callbacks_run ||= []
end
end
class DjPluginTest < Minitest::Test
class TestJob
def perform
end
end
class FailingJob
def perform
raise "Some Error"
end
def max_attempts
1
end
end
def setup
clear_jobs
setup_plugins
end
def test_dj_one_properly_works_with_other_plugins_and_enqueue_callback
clear_run_callbacks_list
enqueue_job(TestJob.new)
assert_equal [:enqueue], run_callbacks_list
end
def test_dj_one_properly_works_with_other_plugins_and_perform_callback
enqueue_job(TestJob.new)
clear_run_callbacks_list
run_worker
assert_equal [:perform], run_callbacks_list
end
def test_dj_one_properly_works_with_other_plugins_and_failure_callback
enqueue_job(FailingJob.new)
clear_run_callbacks_list
run_worker
assert_equal [:perform, :failure], run_callbacks_list
end
private
def clear_jobs
Delayed::Job.delete_all
end
def setup_plugins
Delayed::Worker.plugins = [DjOne::Plugin, OtherPlugin]
Delayed::Worker.setup_lifecycle
end
def clear_run_callbacks_list
OtherPlugin.callbacks_run = []
end
def run_callbacks_list
OtherPlugin.callbacks_run
end
def enqueue_job(job)
Delayed::Job.enqueue(job)
end
def run_worker
Delayed::Worker.new.work_off
end
end
|
piotrj/dj_one
|
test/dj_one_test.rb
|
require 'test_helper'
class DjOneTest < Minitest::Test
class TestJob < Struct.new(:user_id)
def perform
puts "A"
end
def enqueue_id
"test_job_#{user_id}_enqueued"
end
def perform_id
"test_job_#{user_id}_performing"
end
def max_attempts
2
end
def destroy_failed_jobs?
false
end
end
def setup
clear_jobs
clear_workers
end
def test_without_dj_one_you_can_schedule_two_identical_jobs
without_dj_one
user_id = 14
job1 = schedule_test_job(user_id)
job2 = schedule_test_job(user_id)
refute_nil job1.id
refute_nil job2.id
assert_equal 2, Delayed::Job.count
end
def test_it_prevents_scheduling_same_job_twice
with_dj_one
user_id = 14
job1 = schedule_test_job(user_id)
job2 = schedule_test_job(user_id)
refute_nil job1.id
assert_nil job2.id
assert_equal 1, Delayed::Job.count
end
def test_job_changes_unique_id_when_it_is_being_processed
with_dj_one
user_id = 16
job1 = schedule_test_job(user_id)
job1_scheduled_id = job1.unique_id
job1_performing_id = nil
stub_perform do
job1_performing_id = job1.reload.unique_id
end
Delayed::Worker.new.work_off
assert_match /enqueued$/, job1_scheduled_id
assert_match /performing$/, job1_performing_id
end
def test_same_job_cannot_be_processed_at_the_same_time
with_dj_one
user_id = 16
job1 = schedule_test_job(user_id)
mark_as_processing(job1)
job2 = schedule_test_job(user_id)
job_processed = false
stub_perform do
job_processed = true
end
Delayed::Worker.new.work_off
assert_equal false, job_processed
end
def test_duplicate_perform_job_is_rescheduled_for_later
with_dj_one
user_id = 16
job1 = schedule_test_job(user_id)
mark_as_processing(job1)
job2 = schedule_test_job(user_id)
initial_run_at = job2.run_at
Delayed::Worker.new.work_off
assert job2.reload.run_at > initial_run_at
end
def test_when_job_fails_for_the_last_time_unique_id_is_removed
with_dj_one
user_id = 16
job1 = schedule_test_job(user_id)
stub_perform do
raise StandardError.new
end
Delayed::Worker.new.work_off
refute_nil job1.reload.unique_id
job1.update_attributes(run_at: Time.now)
Delayed::Worker.new.work_off
assert_nil job1.reload.unique_id
end
def clear_jobs
Delayed::Job.delete_all
end
def clear_workers
@workers_count = 0
end
def without_dj_one
Delayed::Worker.plugins = []
Delayed::Worker.setup_lifecycle
end
def with_dj_one
Delayed::Worker.plugins = [DjOne::Plugin]
Delayed::Worker.setup_lifecycle
end
def schedule_test_job(user_id)
Delayed::Job.enqueue(TestJob.new(user_id))
end
def stub_perform(&block)
TestJob.send(:define_method, :perform_stub, &block)
TestJob.send(:alias_method, :perform_original, :perform)
TestJob.send(:alias_method, :perform, :perform_stub)
end
def clear_perform_stub
if TestJob.new.respond_to?(:perform_original)
TestJob.send(:undef_method, :perform_stub)
TestJob.send(:alias_method, :perform, :perform_original)
TestJob.send(:undef_method, :perform_original)
end
end
def mark_as_processing(job)
job.update_attributes(unique_id: job.payload_object.perform_id, locked_at: Time.now)
end
end
|
piotrj/dj_one
|
lib/dj_one/templates/install_dj_one_migration.rb
|
superclass = if ActiveRecord.version >= Gem::Version.new(5)
ActiveRecord::Migration[5.0]
else
ActiveRecord::Migration
end
class InstallDjOne < superclass
def self.up
add_column :delayed_jobs, :unique_id, :string
add_index :delayed_jobs, [:unique_id], name: :unique_delayed_jobs, unique: true
end
def self.down
remove_column :delayed_jobs, :unique_id
remove_index :delayed_jobs, name: :unique_delayed_jobs
end
end
|
piotrj/dj_one
|
lib/dj_one.rb
|
require "dj_one/version"
require "active_record"
require "delayed_job"
require "delayed_job_active_record"
require "dj_one/generator"
module DjOne
DEFAULT_DUPLICATE_DELAY = 30.seconds
class Plugin < Delayed::Plugin
callbacks do |lifecycle|
Handler.new(lifecycle)
end
class Handler
def initialize(lifecycle)
lifecycle.around(:enqueue, &method(:enqueue))
lifecycle.around(:perform, &method(:perform))
lifecycle.around(:failure, &method(:failure))
end
def enqueue(job, &proceed)
job.unique_id = get_attribute(job, :enqueue_id)
proceed.call(job)
rescue ActiveRecord::RecordNotUnique
end
def perform(worker, job, &proceed)
job.unique_id = get_attribute(job, :perform_id)
job.save! if job.changed?
proceed.call(worker, job)
rescue ActiveRecord::RecordNotUnique
job.unique_id = job.unique_id_was
job.run_at = calculate_run_at(job)
job.save! if job.changed?
end
def failure(worker, job, &proceed)
job.unique_id = nil
proceed.call(worker, job)
end
def get_attribute(job, method_name)
object = job.payload_object
object.respond_to?(method_name) ? object.public_send(method_name) : nil
rescue Delayed::DeserializationError
nil
end
def calculate_run_at(job)
delay = get_attribute(job, :duplicate_delay) || DEFAULT_DUPLICATE_DELAY
Time.now + delay
end
end
end
end
|
piotrj/dj_one
|
lib/dj_one/generator.rb
|
<gh_stars>1-10
require "rails/generators"
require "rails/generators/active_record"
module DelayedJob
class AddDjOne < Rails::Generators::Base
include ActiveRecord::Generators::Migration
source_root File.expand_path("../templates", __FILE__)
def add_migration
migration_template "install_dj_one_migration.rb", "db/migrate/install_dj_one.rb"
end
end
end
|
nestor-custodio/ed_fi_api
|
lib/ed_fi_client.rb
|
require 'ed_fi/client'
module EdFi; end
|
nestor-custodio/ed_fi_api
|
lib/ed_fi/client/response.rb
|
<reponame>nestor-custodio/ed_fi_api
require 'crapi'
module EdFi; end
class EdFi::Client < Crapi::Client
## Represents an API response. {EdFi::Client::Response EdFi::Client::Response} instances
## initialized from a Hash also allow for reference chaining.
##
class Response
## @param response [Hash, Array]
## The value to encapsulate as an {EdFi::Client::Response EdFi::Client::Response}.
##
## @param client [Crapi::Client]
## The client to use for request chaining.
##
##
## @raise [EdFi::Client::ArgumentError]
##
def initialize(response, client: nil)
@client = client
case response
when Hash
@response = response.to_a.map do |tuple|
(key, value) = tuple.dup
key = key.to_s.underscore.to_sym
value = EdFi::Client::Response.new(value, client: @client) if value.is_a?(Hash) || value.is_a?(Array)
[key, value]
end.to_h.with_indifferent_access
when Array
@response = response.dup.map do |i|
i = EdFi::Client::Response.new(i, client: @client) if i.is_a?(Hash) || i.is_a?(Array)
i
end
when nil, ''
## This can happen for non-body-returning calls.
@response = {}.with_indifferent_access
else
raise EdFi::Client::ArgumentError, %(Unexpected "response" type: #{response.class})
end
end
## Deep updates the associated Crapi::Client] for this and all descendant
## {EdFi::Client::Response EdFi::Client::Response} instances.
##
def client=(client)
@client = client
case @response
when Hash
@response.values.each { |i| i.client = client if i.is_a? EdFi::Client::Response }
when Array
@response.each { |i| i.client = client if i.is_a? EdFi::Client::Response }
end
end
## @private
##
def to_s
@response.to_s
end
## @private
##
def inspect
@response.inspect
end
## rubocop:disable Security/Eval
##
## We're running `eval` on the `#to_s` of a built-in type, which is safe.
## Attempting to let `#as_json` run on its own results in a stack overflow.
## @private
##
def as_json(*args)
eval(to_s).as_json(*args)
end
## rubocop:enable Security/Eval
## rubocop:disable Security/Eval
##
## We're running `eval` on the `#to_s` of a built-in type, which is safe.
## Attempting to let `#to_json` run on its own results in a stack overflow.
## @private
##
def to_json(*args)
eval(to_s).to_json(*args)
end
## rubocop:enable Security/Eval
## rubocop:disable Style/MethodMissing, Metrics/BlockNesting, Metrics/PerceivedComplexity
## @private
##
def method_missing(name, *args, &block)
## Note references are cached.
## To force a refresh on an already-cached reference,
## the method should be called with a single `true` parameter.
## (i.e. `#school` vs `#school(true)`)
if @response.is_a? Hash
## Allow for acceess to response values via dot notation.
return @response[name] if @response.key? name
## Allow for assignment to response values via dot notation.
return @response.send(:'[]=', name[0...-1], *args, &block) if name.to_s.ends_with? '='
## Allow for simple access to referenced resources.
if @client.present?
@references ||= {}
reference = @response["#{name}_reference"].link.href rescue nil
if reference.present?
@references.delete(reference) if args[0] == true
return @references[reference] ||= @client.get(reference)
end
end
end
## All other unaccounted-for method calls should be delegated to the response Hash/Array.
@response.send(name, *args, &block)
end
## rubocop:enable Style/MethodMissing, Metrics/BlockNesting, Metrics/PerceivedComplexity
## @private
##
def respond_to_missing?(name, include_private = false)
( \
( \
(@response.is_a? Hash) \
&& \
( \
@response.key?(name) \
|| \
@response.key?("#{name}_reference".to_sym) \
) \
) \
|| \
@response.respond_to?(name, include_private) \
)
end
end
end
|
nestor-custodio/ed_fi_api
|
lib/ed_fi/client/errors.rb
|
<reponame>nestor-custodio/ed_fi_api
require 'crapi'
module EdFi; end
class EdFi::Client < Crapi::Client
## The base Error class for all {EdFi::Client}-related issues.
##
class Error < ::StandardError
end
## An error relating to missing, invalid, or incompatible method arguments.
##
class ArgumentError < Error
end
## An error relating to a bad request for an authorization *code* or access *token*. This is most
## likely due to a connectivity issue, a bad base URI in the given client, or invalid credentials.
##
class UnableToAuthenticateError < Error
end
end
|
nestor-custodio/ed_fi_api
|
lib/ed_fi/client/version.rb
|
require 'crapi'
## Note we're explicitly declaring "EdFi" as a module here so this file can be directly require'd
## from the base gemspec without issues.
## The EdFi module houses the {EdFi::Client EdFi::Client} in this gem, but should also house future
## EdFi tooling.
##
module EdFi
class Client < Crapi::Client
## The canonical **ed_fi_client** gem version.
##
## This should only ever be updated *immediately* before a release; the commit that updates this
## value should be pushed **by** the `rake release` process.
##
VERSION = '0.1.2'.freeze
end
end
|
nestor-custodio/ed_fi_api
|
lib/ed_fi/client/access_token.rb
|
require 'crapi'
module EdFi; end
class EdFi::Client < Crapi::Client
## The {EdFi::Client::AccessToken EdFi::Client::AccessToken} represents an access token, as
## returned by "/oauth/token" calls.
##
class AccessToken
## An {EdFi::Client::AccessToken EdFi::Client::AccessToken} can be initiialized with the
## "/oauth/token" response Hash. If given, an additional "issued_at" Time value helps to more
## accurately calculate the token's expiration Time.
##
##
## @param access_token [String]
## The actual token value to use as the Bearer token in subsequent requests.
##
## @param token_type [String]
## The token type (e.g. "bearer").
##
## @param issued_at [Time]
## An optional value denoting the Time at which the token was issued.
## If unset, defaults to `Time.current`.
##
## @param expires_in [Numeric]
## The token's lifetime, in seconds.
##
def initialize(access_token:, token_type:, issued_at: Time.current, expires_in:)
@access_token = access_token.dup
@token_type = token_type.dup
@issued_at = issued_at.dup
@expires_in = expires_in.dup
end
## Gives a copy of the token *value*.
##
##
## @return [String]
##
def token
@access_token.dup
end
## Gives the token's *calculated* expiration Time.
##
##
## @return [Time]
##
def expires_at
return 1.second.ago if @access_token.blank?
(@issued_at + @expires_in.seconds)
end
## Denotes whether the token is still "valid", per its (calculated) expiration timesstamp. Note
## that a 5-second window is allotted for the request using the token to complete.
##
##
## @return [true,false]
##
def valid?
safety_window = 5.seconds
Time.current <= (expires_at - safety_window)
end
end
end
|
nestor-custodio/ed_fi_api
|
lib/ed_fi/client/proxy.rb
|
<reponame>nestor-custodio/ed_fi_api<filename>lib/ed_fi/client/proxy.rb<gh_stars>0
require 'crapi'
module EdFi; end
class EdFi::Client < Crapi::Client
## The Crapi::Proxy to {EdFi::Client}'s Crapi::Client.
##
## An {EdFi::Client::Proxy EdFi::Client::Proxy} calls {EdFi::Client::Response#client= #client=}
## on every CRUD-method-generated {EdFi::Client::Response EdFi::Client::Response}.
##
class Proxy < Crapi::Proxy
## CRUD method: GET
##
## All parameters are passed directly through to Crapi::Proxy#get.
##
def get(*args)
response = super
response.client = self
response
end
## CRUD method: DELETE
##
## All parameters are passed directly through to Crapi::Proxy#delete.
##
def delete(*args)
response = super
response.client = self
response
end
## CRUD method: POST
##
## All parameters are passed directly through to Crapi::Proxy#post.
##
def post(*args)
response = super
response.client = self
response
end
## CRUD method: PATCH
##
## All parameters are passed directly through to Crapi::Proxy#patch.
##
def patch(*args)
response = super
response.client = self
response
end
## CRUD method: PUT
##
## All parameters are passed directly through to Crapi::Proxy#put.
##
def put(*args)
response = super
response.client = self
response
end
end
end
|
nestor-custodio/ed_fi_api
|
lib/ed_fi/client/auth.rb
|
require 'crapi'
require 'json'
require 'ed_fi/client/access_token'
require 'ed_fi/client/errors'
module EdFi; end
class EdFi::Client < Crapi::Client
## The {EdFi::Client::Auth EdFi::Client::Auth} represents a complete authentication *mechanism*
## that makes the necessary calls for authorization codes and access tokens, keeps track of any
## token generated, and re-requests new tokens as necessary based on the existing token's
## lifecycle.
##
##
class Auth
## The URI to request an authorization code.
AUTHORIZATION_CODE_URI = '/oauth/authorize'.freeze
## The MIME content type to use for authorization code requests.
AUTHORIZATION_CODE_CONTENT_TYPE = 'application/x-www-form-urlencoded'.freeze
## The URI to request an access token.
ACCESS_TOKEN_URI = '/oauth/token'.freeze
## The MIME content type to use for access token requests.
ACCESS_TOKEN_CONTENT_TYPE = 'application/json'.freeze
## @param client [Crapi::Client]
## The client to use for making auth calls.
##
## @param client_id [String]
## The client id to use for authentication. This is AKA the "api key" / "username".
##
## @param client_secret [String]
## The client secret to use for authentication. This is AKA the "api secret" / "password".
##
def initialize(client:, client_id:, client_secret:)
@client = client
@client_id = client_id
@client_secret = client_secret
@access_token = nil
end
## Gives an access token string that is guaranteed to be valid for *at least* 5 seconds.
##
## Note a new token is requested and returned if the existing token is no longer valid.
##
##
## @return [String]
##
def token
@access_token = new_access_token unless @access_token&.valid?
@access_token.token
end
##
private
##
## Requests and yields a new authorization *code".
##
##
## @raise [EdFi::Client::UnableToAuthenticateError]
##
## @return [String]
##
def new_authorization_code
auth = @client.post(
AUTHORIZATION_CODE_URI,
payload: { Client_id: @client_id, Response_type: 'code' },
headers: { 'Content-Type': AUTHORIZATION_CODE_CONTENT_TYPE }
)
raise EdFi::Client::UnableToAuthenticateError, 'Failed to fetch authorization code.' unless auth&.key? :code
auth[:code]
end
## Requests and yields a new access *token*.
##
##
## @raise [EdFi::Client::UnableToAuthenticateError]
##
## @return [EdFi::Client::AccessToken]
##
def new_access_token
auth = @client.post(
ACCESS_TOKEN_URI,
payload: { Client_id: @client_id, Client_secret: @client_secret,
Code: new_authorization_code, Grant_type: 'authorization_code' },
headers: { 'Content-Type': ACCESS_TOKEN_CONTENT_TYPE }
)
raise EdFi::Client::UnableToAuthenticateError, 'Failed to fetch access token.' unless auth&.key? :access_token
EdFi::Client::AccessToken.new(auth)
end
end
end
|
nestor-custodio/ed_fi_api
|
lib/ed_fi/client.rb
|
require 'active_support/all'
require 'crapi'
require 'ed_fi/client/auth'
require 'ed_fi/client/errors'
require 'ed_fi/client/proxy'
require 'ed_fi/client/response'
require 'ed_fi/client/version'
module EdFi; end
## The main container defined by the **ed_fi_client** gem. Provides a connection mechanism, an
## authentication mechanism, simple CRUD methods ({#delete} / {#get} / {#patch} / {#post} / {#put}),
## and proxy generators.
##
## All other classes defined in this gem (including gem-specific `::Error` derivatives) are
## subclasses of {EdFi::Client EdFi::Client}.
##
class EdFi::Client < Crapi::Client
## The "profile" header content-type template.
PROFILE_MIME_TYPE = 'application/vnd.ed-fi.%<resource>s.%<profile>s.%<access>s+json'.freeze
## @param base_uri [URI, String]
## The base URI the client should use for determining the host to connect to, whether SSH is
## applicable, and the path to the target API.
##
## @param opts [Hash]
## Method options. All options not explicitly listed below are passed on to Crapi::Client.
##
## @option opts [String] :profile
## The profile for which {EdFi::Client#read} and {EdFi::Client#write} will generate headers, if
## any.
##
## @option opts [String] :client_id
## The client id to use for authentication. This is AKA the "api key" / "username".
##
## @option opts [String] :client_secret
## The client secret to use for authentication. This is AKA the "api secret" / "password".
##
##
## @raise [EdFi::Client::ArgumentError]
##
def initialize(base_uri, opts = {})
required_opts = %i[client_id client_secret]
required_opts.each { |opt| raise ArgumentError, "missing keyword: #{opt}" unless opts.key? opt }
super(base_uri, opts)
self.profile = opts[:profile]
## Giving the EdFi::Client::Auth instance its own Crapi client lets us do fancy things with the
## API segmenting stuff ...
##
auth_client = Crapi::Client.new(base_uri, opts)
@auth = EdFi::Client::Auth.new(client: auth_client,
client_id: opts[:client_id],
client_secret: opts[:client_secret])
end
## Sets the profile to use for {EdFi::Client#read} / {EdFi::Client#write} calls.
##
##
## @param profile [String, Symbol]
## The profile for which {EdFi::Client#read} and {EdFi::Client#write} will generate headers.
##
def profile=(profile)
@profile = profile&.to_s&.downcase
end
## rubocop:disable Naming/UncommunicativeMethodParamName
## Returns the header needed to {EdFi::Client#get} a resource with a profile.
##
##
## @param resource [String, Symbol]
## The resource to be read.
##
## @param as [String, Symbol]
## The profile to use. If one has already been set via {EdFi::Client#initialize} or
## {EdFi::Client#profile=}, this value is optional.
##
##
## @return [HashWithIndifferentAccess]
##
def read(resource, as: nil)
self.profile = as if as.present?
mime_type = format(PROFILE_MIME_TYPE, resource: resource, profile: @profile, access: :readable)
{ 'Accept': mime_type }.with_indifferent_access
end
## rubocop:enable Naming/UncommunicativeMethodParamName
## rubocop:disable Naming/UncommunicativeMethodParamName
## Returns the header needed to {EdFi::Client#delete} / {EdFi::Client#patch} / {EdFi::Client#post}
## / {EdFi::Client#put} a resource with a profile.
##
##
## @param resource [String, Symbol]
## The resource to be written.
##
## @param as [String, Symbol]
## The profile to use. If one has already been set via {EdFi::Client#initialize} or
## {EdFi::Client#profile=}, this value is optional.
##
##
## @return [HashWithIndifferentAccess]
##
def write(resource, as: nil)
self.profile = as if as.present?
mime_type = format(PROFILE_MIME_TYPE, resource: resource, profile: @profile, access: :writable)
{ 'Content-Type': mime_type }.with_indifferent_access
end
## rubocop:enable Naming/UncommunicativeMethodParamName
## CRUD methods ...
## CRUD method: DELETE
##
## *headers* and *query* are preprocessed for auth and case conversion, but all parameters are
## otherwise passed through to Crapi::Proxy#delete.
##
def delete(path, headers: {}, query: {})
(headers, query) = preprocess(headers, query)
respond_with super(path, headers: headers, query: query)
end
## CRUD method: GET
##
## *headers* and *query* are preprocessed for auth and case conversion, but all parameters are
## otherwise passed through to Crapi::Proxy#get.
##
def get(path, headers: {}, query: {})
(headers, query) = preprocess(headers, query)
respond_with super(path, headers: headers, query: query)
end
## CRUD method: PATCH
##
## *headers*, *query*, and *payload* are preprocessed for auth and case conversion, but all
## parameters are otherwise passed through to Crapi::Proxy#patch.
##
def patch(path, headers: {}, query: {}, payload: {})
(headers, query, payload) = preprocess(headers, query, payload)
respond_with super(path, headers: headers, query: query, payload: payload)
end
## CRUD method: POST
##
## *headers*, *query*, and *payload* are preprocessed for auth and case conversion, but all
## parameters are otherwise passed through to Crapi::Proxy#post.
##
def post(path, headers: {}, query: {}, payload: {})
(headers, query, payload) = preprocess(headers, query, payload)
respond_with super(path, headers: headers, query: query, payload: payload)
end
## CRUD method: PUT
##
## *headers*, *query*, and *payload* are preprocessed for auth and case conversion, but all
## parameters are otherwise passed through to Crapi::Proxy#put.
##
def put(path, headers: {}, query: {}, payload: {})
(headers, query, payload) = preprocess(headers, query, payload)
respond_with super(path, headers: headers, query: query, payload: payload)
end
## API segment proxies ...
## Convenience proxy generator for v2.0 API access, also addomg the school year you'd like to
## access, if given.
##
##
## @param period [Integer]
## The school year to be accessed. (To access the v2.0 API for school year 2017-2018, call
## `v2(2017)`.)
##
##
## @return [EdFi::Client::Proxy]
##
def v2(period = nil)
period = period.to_i
@v2 = {} if @v2.nil?
@v2[period] ||= begin
path = '/api/v2.0'
path += "/#{period}" if period.nonzero?
EdFi::Client::Proxy.new(add: path, to: self)
end
end
##
private
##
## Generates an auth header, with a valid Bearer token.
##
##
## @return [HashWithIndifferentAccess]
##
def auth_header
{ 'Authorization': "Bearer #{@auth.token}" }.with_indifferent_access
end
## Carries out preprocessing for headers, query data, and payload data, returning processed
## *copies* of the given values.
##
##
## @param headers [Hash]
## The headers to preprocess. A copy of this value is returned with auth headers added, so long
## as no key conflicts arise.
##
## @param query [Hash]
## The querystring values to preprocess. Keys will be case-converted where necessary.
##
## @param payload [Hash]
## The payload values to preprocess. Keys will be case-converted where necessary.
##
##
## @return [(Hash, Hash, Hash)]
##
def preprocess(headers, query = nil, payload = nil)
payload = payload.as_json if payload.is_a? EdFi::Client::Response
headers = auth_header.merge(headers)
query = query.deep_transform_keys { |key| key.to_s.camelize(:lower) } if query.is_a? Hash
payload = payload.deep_transform_keys { |key| key.to_s.camelize(:lower) } if payload.is_a? Hash
[headers, query, payload]
end
## Returns an {EdFi::Client::Response EdFi::Client::Response} for the given API resonse value.
##
##
## @param response [Hash, Array]
## The API response Hash/Array to convert to an {EdFi::Client::Response EdFi::Client::Response}.
##
##
## @return [EdFi::Client::Response]
##
def respond_with(response)
EdFi::Client::Response.new(response, client: self)
end
end
|
ongmin/9gag
|
db/migrate/20160127064756_add_image_to_posts.rb
|
class AddImageToPosts < ActiveRecord::Migration
def up
add_attachment :posts, :image
end
def down
remove_attachment :posts, :image
end
end
|
ongmin/9gag
|
app/controllers/landing_controller.rb
|
<gh_stars>1-10
class LandingController < ApplicationController
def index
end
end
|
ongmin/9gag
|
app/models/post.rb
|
class Post < ActiveRecord::Base
has_attached_file :image, styles: { medium: "300x300>" }
validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/
validates :title, :presence => true
end
|
andre-lgf/searates
|
lib/searates.rb
|
<filename>lib/searates.rb
require "searates/version"
require 'searates/configuration'
require 'searates/errors'
require 'searates/api'
module Searates
class << self
attr_accessor :configuration
end
def self.configuration
@configuration ||= Configuration.new
end
def self.reset
@configuration = Configuration.new
end
def self.configure
yield(configuration)
end
end
|
andre-lgf/searates
|
spec/searates_spec.rb
|
RSpec.describe Searates do
it "has a version number" do
expect(Searates::VERSION).not_to be nil
end
describe Searates::Configuration do
context "with valid api key" do
it "should return the api key" do
expect(Searates.configuration.api_key).to eq(ENV['SEARATES_API_KEY'])
end
context "logistics explorer API" do
context "FLC rates" do
context "with invalid parameters" do
it "should raise error" do
expect{ Searates::API::LogisticsExplorer.get_fcl_rates(@lat_from, nil, @lat_to, @lng_to) }.to raise_error(Searates::Errors::API::MissingParameters)
end
end
context "with valid parameters" do
it "should return fcl rates" do
response = Searates::API::LogisticsExplorer.get_fcl_rates(@lat_from, @lng_from, @lat_to, @lng_to)
expect(response['rates'].size).to be > 0
end
it "should return fcl rates with route info" do
response = Searates::API::LogisticsExplorer.get_fcl_rates(@lat_from, @lng_from, @lat_to, @lng_to, true)
expect(response['route'].size).to be > 0
end
end
end
context "LCL rates" do
context "with valid parameters" do
it "should return lcl rates" do
response = Searates::API::LogisticsExplorer.get_lcl_rates(@lat_from, @lng_from, @lat_to, @lng_to, @weight, @volume)
expect(response['rates']['lcl'].size).to be > 0
end
end
context "with invalid parameters" do
it "should raise error" do
expect{ Searates::API::LogisticsExplorer.get_lcl_rates(@lat_from, @lng_from, @lat_to, nil, @weight, @volume) }.to raise_error(Searates::Errors::API::MissingParameters)
end
end
end
context "Sea route" do
context "with valid parameters" do
it "should return sea route" do
response = Searates::API::LogisticsExplorer.get_sea_route(@lat_from, @lng_from, @lat_to, @lng_to)
expect(response['route'].size).to be > 1
end
end
context "with invalid parameters" do
it "should raise error" do
expect{ Searates::API::LogisticsExplorer.get_sea_route(nil, @lng_from, @lat_to, @lng_to) }.to raise_error(Searates::Errors::API::MissingParameters)
end
end
end
context "Air rates" do
context "with valid parameters" do
it "should return air rates" do
response = Searates::API::LogisticsExplorer.get_air_rates(@lat_from, @lng_from, @lat_to, @lng_to, @weight)
expect(response['rates']['air'].size).to be > 0
end
end
context "with invalid parameters" do
it "should raise error" do
expect{ Searates::API::LogisticsExplorer.get_air_rates(@lat_from, @lng_from, @lat_to, nil, @weight) }.to raise_error(Searates::Errors::API::MissingParameters)
end
end
end
context "Rail rates" do
context "with valid parameters" do
it "should return rail rates" do
response = Searates::API::LogisticsExplorer.get_rail_rates(@lat_from, @lng_from, @lat_to, @lng_to)
expect(response['rates'].size).to be > 0
end
end
context "with invalid parameters" do
it "should raise error" do
expect{ Searates::API::LogisticsExplorer.get_rail_rates(@lat_from, @lng_from, nil, @lng_to) }.to raise_error(Searates::Errors::API::MissingParameters)
end
end
end
context "Road rates" do
context "with valid parameters" do
context "without optional parameters" do
it "should return road rates" do
response = Searates::API::LogisticsExplorer.get_road_rates(@lat_from, @lng_from, @lat_to, @lng_to, @weight, @volume)
expect(response['rates'].size).to be > 0
end
end
context "determining the type" do
it "should return road rates" do
response = Searates::API::LogisticsExplorer.get_road_rates(@lat_from, @lng_from, @lat_to, @lng_to, @weight, @volume, 'FCL')
expect(response['rates'].size).to be > 0
end
end
context "determining the size of container" do
it "should return road rates" do
response = Searates::API::LogisticsExplorer.get_road_rates(@lat_from, @lng_from, @lat_to, @lng_to, @weight, @volume, 'CONTAINER', '40st')
expect(response['rates'].size).to be > 0
end
end
end
context "with invalid parameters" do
it "should raise error" do
expect{ Searates::API::LogisticsExplorer.get_road_rates(@lat_from, @lng_from, @lat_to, @lng_to, @weight, nil) }.to raise_error(Searates::Errors::API::MissingParameters)
end
context "with invalid type" do
it "should raise error" do
expect{ Searates::API::LogisticsExplorer.get_road_rates(@lat_from, @lng_from, @lat_to, @lng_to, @weight, @volume, 'ABC', '40ref') }.to raise_error(Searates::Errors::API::InvalidParameterValue)
end
end
context "with invalid size" do
it "should raise error" do
expect{ Searates::API::LogisticsExplorer.get_road_rates(@lat_from, @lng_from, @lat_to, @lng_to, @weight, @volume, 'FCL', '40') }.to raise_error(Searates::Errors::API::InvalidParameterValue)
end
end
end
end
end
end
context "without valid api key" do
before do
Searates.reset
end
it "should return an error" do
expect { Searates.configuration.api_key }.to raise_error(Searates::Errors::Configuration)
end
end
end
end
|
andre-lgf/searates
|
lib/searates/api.rb
|
<reponame>andre-lgf/searates<gh_stars>1-10
require 'searates/api/logistics_explorer'
require 'open-uri'
|
andre-lgf/searates
|
spec/spec_helper.rb
|
<reponame>andre-lgf/searates
require "bundler/setup"
require "searates"
RSpec.configure do |config|
# Enable flags like --only-failures and --next-failure
config.example_status_persistence_file_path = ".rspec_status"
# Disable RSpec exposing methods globally on `Module` and `main`
config.disable_monkey_patching!
config.expect_with :rspec do |c|
c.syntax = :expect
end
config.before(:all) do
Searates.configure do |config|
config.api_key = ENV['SEARATES_API_KEY']
end
end
config.before(:each) do
@lat_from = 24.8607343
@lng_from = 67.00113639999995
@lat_to = 46.482526
@lng_to = 30.723309500000028
@weight = 1000
@volume = 1
end
end
|
andre-lgf/searates
|
lib/searates/configuration.rb
|
module Searates
class Configuration
attr_accessor :api_key
def initialize
@api_key ||= nil
end
def api_key
raise Searates::Errors::Configuration, 'SeaRates API Key missing!' unless @api_key
@api_key
end
end
end
|
andre-lgf/searates
|
lib/searates/api/logistics_explorer.rb
|
module Searates
module API
class LogisticsExplorer
BASE_URL = 'https://sirius.searates.com/port/api-'
def self.get_fcl_rates(lat_from, long_from, lat_to, long_to, route_info=false)
[lat_from, long_from, lat_to, long_to].each{|param| raise Searates::Errors::API::MissingParameters, "Missing parameter: #{param}" unless param}
request_url = "#{BASE_URL}fcl?apiKey=#{Searates.configuration.api_key}&lat_from=#{lat_from}&lng_from=#{long_from}&lat_to=#{lat_to}&lng_to=#{long_to}&route_info=#{route_info}"
response = JSON.parse(URI.open(request_url).read)
end
def self.get_lcl_rates(lat_from, long_from, lat_to, long_to, weight, volume)
[lat_from, long_from, lat_to, long_to, weight, volume].each{|param| raise Searates::Errors::API::MissingParameters, "Missing parameter: #{param}" unless param}
request_url = "#{BASE_URL}lcl?apiKey=#{Searates.configuration.api_key}&lat_from=#{lat_from}&lng_from=#{long_from}&lat_to=#{lat_to}&lng_to=#{long_to}&weight=#{weight}&volume=#{volume}"
response = JSON.parse(URI.open(request_url).read)
end
def self.get_sea_route(lat_from, long_from, lat_to, long_to)
[lat_from, long_from, lat_to, long_to].each{|param| raise Searates::Errors::API::MissingParameters, "Missing parameter: #{param}" unless param}
request_url = "#{BASE_URL}path?apiKey=#{Searates.configuration.api_key}&lat_from=#{lat_from}&lng_from=#{long_from}&lat_to=#{lat_to}&lng_to=#{long_to}"
response = JSON.parse(URI.open(request_url).read)
end
def self.get_air_rates(lat_from, long_from, lat_to, long_to, weight)
[lat_from, long_from, lat_to, long_to, weight].each{|param| raise Searates::Errors::API::MissingParameters, "Missing parameter: #{param}" unless param}
request_url = "#{BASE_URL}air?apiKey=#{Searates.configuration.api_key}&lat_from=#{lat_from}&lng_from=#{long_from}&lat_to=#{lat_to}&lng_to=#{long_to}&weight=#{weight}"
response = JSON.parse(URI.open(request_url).read)
end
def self.get_rail_rates(lat_from, long_from, lat_to, long_to)
[lat_from, long_from, lat_to, long_to].each{|param| raise Searates::Errors::API::MissingParameters, "Missing parameter: #{param}" unless param}
request_url = "#{BASE_URL}rail?apiKey=#{Searates.configuration.api_key}&lat_from=#{lat_from}&lng_from=#{long_from}&lat_to=#{lat_to}&lng_to=#{long_to}"
response = JSON.parse(URI.open(request_url).read)
end
def self.get_road_rates(lat_from, long_from, lat_to, long_to, weight, volume, type='CONTAINER', container='20st')
[lat_from, long_from, lat_to, long_to, weight, volume, type, container].each{|param| raise Searates::Errors::API::MissingParameters, "Missing parameter: #{param}" unless param}
request_url = "#{BASE_URL}road?apiKey=#{Searates.configuration.api_key}&lat_from=#{lat_from}&lng_from=#{long_from}&lat_to=#{lat_to}&lng_to=#{long_to}&weight=#{weight}&volume=#{volume}"
if type
raise Searates::Errors::API::InvalidParameterValue unless ['FCL', 'LCL', 'CONTAINER'].include? type.upcase
request_url += "&type=#{type.upcase}"
end
if container
raise Searates::Errors::API::InvalidParameterValue unless container.downcase =~ /20st|40st|40hq|20ref|40ref/
request_url += "&container=#{container.downcase}"
end
response = JSON.parse(URI.open(request_url).read)
end
end
end
end
|
andre-lgf/searates
|
lib/searates/errors.rb
|
module Searates
module Errors
class Configuration < StandardError; end
module API
class MissingParameters < StandardError; end
class InvalidParameterValue < StandardError; end
end
end
end
|
travis-ci/travis-logger
|
lib/travis/logger.rb
|
<reponame>travis-ci/travis-logger
require 'logger'
module Travis
class Logger < ::Logger # TODO
require 'travis/logger/format'
class << self
def new(io, config = {})
configure(super(io), config)
end
def configure(logger, config)
logger.formatter = Format.new(config[:logger])
logger.level = level_for(config)
logger
end
def level_for(config)
level = config.fetch(:logger, {})[:level] || config[:log_level] || :debug
Logger.const_get(level.to_s.upcase)
end
end
[:fatal, :error, :warn, :info, :debug].each do |level|
define_method(level) do |msg, options = {}|
msg = msg.dup
options.dup.tap do |opts|
opts.delete(:progname)
class << msg
attr_reader :l2met_args
end
msg.instance_variable_set(:@l2met_args, opts)
end
super(msg)
end
end
end
end
|
travis-ci/travis-logger
|
spec/logger/format_spec.rb
|
<filename>spec/logger/format_spec.rb<gh_stars>0
require 'stringio'
describe Travis::Logger::Format do
let(:io) { StringIO.new }
let(:log) { io.string }
let(:formatter) { Travis::Logger::Format.new }
let(:logger) { Travis::Logger.new(io).tap { |logger| logger.formatter = formatter } }
context 'when using traditional format' do
before :each do
ENV.delete('TRAVIS_PROCESS_NAME')
end
it 'includes the severity as a single char' do
logger.info('message')
expect(log).to match(/^I /)
end
it 'includes the message' do
logger.info('message')
expect(log).to match(/ message$/)
end
it 'includes the timestamp if config.time_format is given' do
logger.formatter = Travis::Logger::Format.new(time_format: '%Y-%m-%dT%H:%M:%S.%6N%:z')
logger.info('message')
expect(log).to match(/^[\d]{4}-[\d]{2}-[\d]{2}T[\d]{2}:[\d]{2}:[\d]{2}\.[\d]{6}[-+][\d]{2}:[\d]{2}/)
end
it 'does not include the timestamp if config.time_format is not given' do
logger.info('message')
expect(log).to_not match(/^[\d]{4}-[\d]{2}-[\d]{2}T[\d]{2}:[\d]{2}:[\d]{2}\.[\d]{6}[-+][\d]{2}:[\d]{2}/)
end
it 'includes the current thread id if config.thread_id is given' do
logger.formatter = Travis::Logger::Format.new(thread_id: true)
logger.info('message')
expect(log).to include(Thread.current.object_id.to_s[-4, 4])
end
it 'does not include the current thread id if config.thread_id is not given' do
logger.info('message')
expect(log).to_not include(Thread.current.object_id.to_s[-4, 4])
end
it 'includes the current process id if config.process_id is given' do
logger.formatter = Travis::Logger::Format.new(process_id: true)
logger.info('message')
expect(log).to include(Process.pid.to_s)
end
it 'does not include the current process id if config.process_id is not given' do
logger.info('message')
expect(log).to_not include(Process.pid.to_s)
end
it 'includes the process name if ENV["TRAVIS_PROCESS_NAME"] is present' do
ENV['TRAVIS_PROCESS_NAME'] = 'hub.1'
logger.info('message')
expect(log).to include('app[hub.1]: ')
end
it 'does not include the process name if ENV["TRAVIS_PROCESS_NAME"] is not present' do
logger.info('message')
expect(log).to_not include('app[hub.1]: ')
end
it 'logs a string' do
logger.info('hi')
expect(log).to eq("I hi\n")
end
it 'logs a exception' do
exception = StandardError.new('kaputt!').tap { |e| e.set_backtrace(['line 1', 'line 2']) }
logger.info(exception)
expect(log).to eq("I StandardError: kaputt!\nline 1\nline 2\n")
end
it 'logs an array' do
logger.info(%w{banana apple orange})
expect(log).to eq("I banana\napple\norange\n")
end
it 'logs a hash' do
logger.info(attr1: 'value1', attr2: 2)
expect(log).to eq("I attr1=value1 attr2=2\n")
end
it 'logs any object' do
logger.info(Object.new)
expect(log).to match(/\AI #<Object.+>\n\z/)
end
it 'logs frozen objects' do
logger.info('hi'.freeze)
expect(log).to eq("I hi\n")
end
it 'formatter works with message without l2met_args' do
now = Time.now
expect(formatter.call('DEBUG', now, 'program', 'completely normal message')).to include('completely normal message')
end
end
context 'when using l2met format' do
let(:formatter) { Travis::Logger::Format.new(format_type: 'l2met') }
before :each do
ENV.delete('TRAVIS_PROCESS_NAME')
end
it 'includes the severity' do
logger.info('message')
expect(log).to include('level=info')
end
it 'includes the quoted message' do
logger.info('message with spaces')
expect(log).to include('msg="message with spaces"')
end
it 'includes the message' do
logger.info('message')
expect(log).to include('msg=message')
end
it 'includes the timestamp if config.time_format is given' do
logger.formatter = Travis::Logger::Format.new(format_type: 'l2met', time_format: '%Y-%m-%dT%H:%M:%S.%6N%:z')
logger.info('message')
expect(log).to match(/time=[\d]{4}-[\d]{2}-[\d]{2}T[\d]{2}:[\d]{2}:[\d]{2}\.[\d]{6}[\-\+][\d]{2}:[\d]{2}/)
end
it 'includes the timestamp as iso8601 if config.time_format is not given' do
logger.info('message')
expect(log).to match(/time=[\d]{4}-[\d]{2}-[\d]{2}T[\d]{2}:[\d]{2}:[\d]{2}[\-\+][\d]{2}:[\d]{2}/)
end
it 'includes the current thread id if config.thread_id is given' do
logger.formatter = Travis::Logger::Format.new(format_type: 'l2met', thread_id: true)
logger.info('message')
expect(log).to include("tid=#{Thread.current.object_id}")
end
it 'does not include the current thread id if config.thread_id is not given' do
logger.info('message')
expect(log).to_not include("tid=#{Thread.current.object_id}")
end
it 'includes the current process id if config.process_id is given' do
logger.formatter = Travis::Logger::Format.new(format_type: 'l2met', process_id: true)
logger.info('message')
expect(log).to include("pid=#{Process.pid}")
end
it 'does not include the current process id if config.process_id is not given' do
logger.info('message')
expect(log).to_not include("pid=#{Process.pid}")
end
it 'includes the current thread id if config.thread_id is given' do
logger.formatter = Travis::Logger::Format.new(format_type: 'l2met', thread_id: true)
logger.info('message')
expect(log).to include("tid=#{Thread.current.object_id}")
end
it 'does not include the current thread id if config.thread_id is not given' do
logger.info('message')
expect(log).to_not include("tid=#{Thread.current.object_id}")
end
it 'includes the process name if ENV["TRAVIS_PROCESS_NAME"] is present' do
ENV['TRAVIS_PROCESS_NAME'] = 'hub.1'
logger.info('message')
expect(log).to include('app=hub.1')
end
it 'includes arbitrary key=value pairs' do
logger.info('message', foo: 'bar', energy: 9001)
expect(log).to include('foo=bar')
expect(log).to include('energy=9001')
end
it 'does not include the process name if ENV["TRAVIS_PROCESS_NAME"] is not present' do
logger.info('message')
expect(log).to_not include('app=hub.1')
end
end
end
|
travis-ci/travis-logger
|
lib/travis/logger/format.rb
|
require 'time'
module Travis
class Logger
class Format
def initialize(config = {})
@config = config || {}
end
def call(severity, time, progname, message)
l2met_args = message.respond_to?(:l2met_args) ? message.l2met_args : {}
send(
"format_#{config[:format_type] || 'traditional'}",
severity, time, progname, message_to_string(message), l2met_args
)
end
def message_to_string(message)
message = message.join("\n") if message.respond_to?(:join)
message = case message
when Exception
exception = message
"#{exception.class.name}: #{exception.message}".tap do |s|
s << "\n#{exception.backtrace.join("\n")}" if exception.backtrace
end
when Hash
message.map do |k, v|
"#{k}=#{v.to_s}"
end.join(' ')
when String
message.chomp
else
message.inspect
end
message + "\n"
end
private
attr_reader :config
def format_traditional(severity, time, progname, message, l2met_args)
traditional_format % log_record_vars(severity, time, progname, message)
end
def format_l2met(severity, time, progname, message, message_l2met_args)
vars = log_record_vars(severity, time, progname, message)
l2met_args = {
time: vars[:formatted_time],
level: vars[:severity_downcase].to_sym,
msg: vars[:message].strip
}
l2met_args[:tid] = vars[:thread_id] if config[:thread_id]
l2met_args[:pid] = vars[:process_id] if config[:process_id]
l2met_args[:app] = vars[:process_name] if ENV['TRAVIS_PROCESS_NAME']
l2met_args.merge!(message_l2met_args)
l2met_args_to_record(l2met_args).strip + "\n"
end
def log_record_vars(severity, time, progname, message)
{
message: message.to_s,
process_id: Process.pid,
process_name: ENV['TRAVIS_PROCESS_NAME'],
progname: progname,
severity: severity,
severity_downcase: severity.downcase,
severity_initial: severity[0, 1],
thread_id: Thread.current.object_id,
time: time
}.tap do |v|
if time_format
v[:formatted_time] = time.strftime(time_format)
elsif config[:format_type] == 'l2met'
v[:formatted_time] = time.iso8601
end
end
end
def time_format
@time_format ||= config[:time_format]
end
def l2met_args_to_record(l2met_args)
args = l2met_args.dup
''.tap do |s|
(builtin_l2met_args + (args.keys.sort - builtin_l2met_args)).each do |key|
value = args.delete(key)
value = value.inspect if value.respond_to?(:include?) && value.include?(' ')
s << "#{key}=#{value} "
end
end
end
def builtin_l2met_args
@builtin_l2met_args ||= %w(time level msg).map(&:to_sym)
end
def traditional_format
@traditional_format ||= ''.tap do |s|
s << '%{formatted_time} ' if time_format
s << '%{severity_initial} '
s << 'app[%{process_name}]: ' if ENV['TRAVIS_PROCESS_NAME']
s << 'PID=%{process_id} ' if config[:process_id]
s << 'TID=%{thread_id} ' if config[:thread_id]
s << '%{message}'
end
end
end
end
end
|
erdnussflips/jazzy
|
lib/jazzy/gem_version.rb
|
<filename>lib/jazzy/gem_version.rb
module Jazzy
VERSION = '0.10.0'.freeze unless defined? Jazzy::VERSION
end
|
erdnussflips/jazzy
|
lib/jazzy/doc.rb
|
require 'date'
require 'pathname'
require 'mustache'
require 'jazzy/config'
require 'jazzy/gem_version'
require 'jazzy/jazzy_markdown'
module Jazzy
class Doc < Mustache
include Config::Mixin
self.template_name = 'doc'
def copyright
copyright = config.copyright || (
# Fake date is used to keep integration tests consistent
date = ENV['JAZZY_FAKE_DATE'] || DateTime.now.strftime('%Y-%m-%d')
year = date[0..3]
"© #{year} [#{config.author_name}](#{config.author_url}). " \
"All rights reserved. (Last updated: #{date})"
)
Markdown.render_copyright(copyright).chomp
end
def jazzy_version
# Fake version is used to keep integration tests consistent
ENV['JAZZY_FAKE_VERSION'] || Jazzy::VERSION
end
def objc_first?
config.objc_mode && config.hide_declarations != 'objc'
end
def language
objc_first? ? 'Objective-C' : 'Swift'
end
def language_stub
objc_first? ? 'objc' : 'swift'
end
def module_version
config.version_configured ? config.version : nil
end
def docs_title
if config.title_configured
config.title
elsif config.version_configured
# Fake version for integration tests
version = ENV['JAZZY_FAKE_MODULE_VERSION'] || config.version
"#{config.module_name} #{version} Docs"
else
"#{config.module_name} Docs"
end
end
end
end
|
tysonholub/frendms-rails
|
frendms-rails.gemspec
|
<reponame>tysonholub/frendms-rails
# -*- encoding: utf-8 -*-
# stub: frendms-rails 0.1.0 ruby lib
Gem::Specification.new do |s|
s.name = "frendms-rails"
s.version = "0.3.2"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.metadata = { "allowed_push_host" => "https://rubygems.org" } if s.respond_to? :metadata=
s.require_paths = ["lib"]
s.authors = ["<NAME>"]
s.bindir = "exe"
s.date = "2016-01-27"
s.description = "Click and edit any html element. Changes are saved to the database via ajax. When the page is loaded the changes will be injected into that element."
s.email = ["<EMAIL>"]
s.files = [".gitignore", ".travis.yml", "CODE_OF_CONDUCT.md", "Gemfile", "LICENSE.txt", "README.md", "Rakefile", "app/controllers/frendms/element_controller.rb", "app/models/frendms/element.rb", "bin/console", "bin/setup", "config/routes.rb", "frendms-rails.gemspec", "lib/frendms/rails.rb", "lib/frendms/rails/version.rb", "lib/generators/frendms/frendms_generator.rb", "lib/generators/frendms/templates/migration.rb", "vendor/assets/javascripts/dompath.js", "vendor/assets/javascripts/frendms.js", "vendor/assets/stylesheets/frendms.css"]
s.homepage = "https://github.com/tysonholub/frendms-rails"
s.licenses = ["MIT"]
s.rubygems_version = "2.2.2"
s.summary = "The Front End Management System"
if s.respond_to? :specification_version then
s.specification_version = 4
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_development_dependency(%q<bundler>, ["~> 1.10"])
s.add_development_dependency(%q<rake>, ["~> 10.0"])
else
s.add_dependency(%q<bundler>, ["~> 1.10"])
s.add_dependency(%q<rake>, ["~> 10.0"])
end
else
s.add_dependency(%q<bundler>, ["~> 1.10"])
s.add_dependency(%q<rake>, ["~> 10.0"])
end
end
|
tysonholub/frendms-rails
|
config/routes.rb
|
Rails.application.routes.draw do
get '/element/all' => 'frendms/element#get_elements'
put '/element/update' => 'frendms/element#update_element'
end
|
tysonholub/frendms-rails
|
app/models/frendms/element.rb
|
<gh_stars>0
module Frendms
class Element < ActiveRecord::Base
end
end
|
tysonholub/frendms-rails
|
app/controllers/frendms/element_controller.rb
|
module Frendms
class ElementController < ::ApplicationController
def get_elements
e = Element.where('frender = ?', params[:frender])
respond_to do |format|
format.json { render :json => e.to_json(:only => [:elementId, :elementIndex, :text]) }
end
end
def update_element
if user_signed_in?
e = Element.find_by(:elementId => params[:id], :elementIndex => params[:index], :frender => params[:frender])
if(params[:text].length > 0)
if e.nil?
e = Element.new
e.frender = params[:frender]
e.elementId = params[:id]
e.elementIndex = params[:index]
end
e.text = params[:text]
e.save
respond_to do |format|
format.json { render :json => e.to_json }
end
else
if not e.nil?
e.delete
respond_to do |format|
format.json { render :json => { 'resp' => "deleted element record for element id '#{params[:id]}'" } }
end
else
respond_to do |format|
format.json { render :json => { 'resp' => 'nothing to do' } }
end
end
end
else
respond_to do |format|
format.json { render :json => { 'error' => 'you must be logged in to commit changes' } }
end
end
end
end
end
|
dingdayu/homebrew-cask
|
Casks/fl-studio.rb
|
<gh_stars>1-10
cask "fl-studio" do
version "20.8.4.2040"
sha256 "6edeb7e549fd4bbedcdd90324133ae2ac829bd9fb7f2dff6cf045d17419a3b1e"
url "https://demodownload.image-line.com/flstudio/flstudio_mac_#{version}.dmg"
name "FL Studio"
desc "Digital audio production application"
homepage "https://www.image-line.com/flstudio/"
livecheck do
url "https://support.image-line.com/redirect/flstudio20_mac_installer"
strategy :header_match
end
pkg "Install FL Studio.pkg"
uninstall pkgutil: "com.Image-Line.pkg.FLStudio64"
zap trash: [
"~/Library/Caches/com.image-line.flstudio",
"~/Library/Preferences/com.image-line.flstudio.plist",
]
end
|
dingdayu/homebrew-cask
|
Casks/grammarly.rb
|
cask "grammarly" do
version "1.5.77"
sha256 :no_check
url "https://download-editor.grammarly.com/osx/Grammarly.dmg"
name "Grammarly"
desc "Utility to fix grammar errors and style issues in text"
homepage "https://www.grammarly.com/"
livecheck do
url :url
strategy :extract_plist do |versions|
versions.values.map(&:version).compact.first
end
end
auto_updates true
app "Grammarly.app"
zap trash: [
"~/Library/Application Support/Grammarly",
"~/Library/Caches/com.grammarly.DesktopEditor",
"~/Library/Caches/com.grammarly.DesktopEditor.ShipIt",
"~/Library/Logs/Grammarly",
"~/Library/Preferences/com.grammarly.DesktopEditor.helper.plist",
"~/Library/Preferences/com.grammarly.DesktopEditor.plist",
"~/Library/Saved Application State/com.grammarly.DesktopEditor.savedState",
]
end
|
dressipi/css_splitter
|
lib/css_splitter.rb
|
<reponame>dressipi/css_splitter
require 'tilt'
require 'sprockets'
require 'css_splitter/application_helper'
require 'css_splitter/engine'
require 'css_splitter/splitter'
require 'css_splitter/version'
module CssSplitter
module Sprockets
class Template < ::Tilt::Template
def self.engine_initialized?
true
end
def initialize_engine
end
def prepare
end
def evaluate(scope, locals, &block)
part = scope.pathname.extname =~ /(\d+)$/ && $1 || 0
CssSplitter::Splitter.split data, part.to_i
end
end
end
end
Sprockets::Engines
Sprockets.register_engine '.split2', CssSplitter::Sprockets::Template
|
dressipi/css_splitter
|
lib/css_splitter/engine.rb
|
module CssSplitter
module Sprockets
class Engine < ::Rails::Engine
isolate_namespace CssSplitter
config.to_prepare do
ApplicationController.helper(CssSplitter::ApplicationHelper)
end
end
end
end
|
dressipi/css_splitter
|
test/dummy/app/controllers/tests_controller.rb
|
class TestsController < ApplicationController
def test
end
end
|
dressipi/css_splitter
|
lib/css_splitter/splitter.rb
|
<gh_stars>0
module CssSplitter
class Splitter
MAX_SELECTORS_DEFAULT = 4095
class << self
def split(data, part=1, max_selectors=MAX_SELECTORS_DEFAULT)
rules = StringIO.new(data).readlines('}')
return if rules.first.nil?
charset_statement, rules[0] = rules.first.partition(/^\@charset[^;]+;/)[1,2]
output = charset_statement
output << rules[index_for_rule_with_max_selector(rules, max_selectors)..-1].join
output
end
private
def count_selectors_of_rule(rule)
rule.partition(/\{/).first.scan(/,/).count.to_i + 1
end
def index_for_rule_with_max_selector(rules, max_selectors)
selectors_count = 0
rules.each_with_index do |rule, index|
rule_selectors_count = count_selectors_of_rule(rule)
selectors_count += rule_selectors_count
return index if selectors_count > max_selectors
end
rules.length -1
end
end
end
end
|
dressipi/css_splitter
|
lib/css_splitter/application_helper.rb
|
module CssSplitter
module ApplicationHelper
def split_stylesheet_link_tag(*sources)
original_sources = sources.dup
options = sources.extract_options!
sources.collect!{ |source| head, tail = source.split('.'); "#{head}_split2.#{Array.wrap(tail).join('.')}" }
sources << options
[
stylesheet_link_tag(*original_sources),
"<!--[if lte IE 9]>",
stylesheet_link_tag(*sources),
"<![endif]-->"
].join("\n").html_safe
end
end
end
|
dressipi/css_splitter
|
css_splitter.gemspec
|
<reponame>dressipi/css_splitter<gh_stars>0
$:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "css_splitter/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "css_splitter"
s.version = CssSplitter::VERSION
s.authors = ["<NAME>", "<NAME>"]
s.email = ["<EMAIL>", "<EMAIL>"]
s.homepage = "https://github.com/zweilove/css_splitter"
s.summary = "CSS stylesheet splitter for Rails"
s.description = "Gem for splitting up stylesheets that go beyond the IE limit of 4095 selectors, for Rails 3.1+ apps using the Asset Pipeline."
s.files = Dir["{app,config,db,lib}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.md"]
s.test_files = Dir["test/**/*"]
s.add_dependency "rails", "> 3.1", "< 5.0"
end
|
dressipi/css_splitter
|
test/dummy/config/routes.rb
|
<filename>test/dummy/config/routes.rb
Rails.application.routes.draw do
get "tests/test"
root :to => "tests#test"
end
|
dressipi/css_splitter
|
test/css_splitter_test.rb
|
require 'test_helper'
class CssSplitterTest < ActiveSupport::TestCase
test "truth" do
assert_kind_of Module, CssSplitter
end
end
|
MortarStone/planning_center_online-ruby
|
examples/helpers/emails.rb
|
# frozen_string_literal: true
def print_emails(list)
print_list('email', 'id', list)
end
def print_email(item)
print_item('email', item)
end
def email_columns
%w[
id
address
location
primary
blocked
]
end
|
MortarStone/planning_center_online-ruby
|
spec/planning_center/endpoints/recurring_donation_designations_spec.rb
|
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe PlanningCenter::Endpoints::RecurringDonationDesignations do
let!(:client) { FactoryBot.build(:client) }
describe '#recurring_donation_designations', :vcr do
before do
@recurring_donation_designations = client.recurring_donation_designations(358_916)
end
it 'returns an array' do
expect(@recurring_donation_designations['data']).to be_an(Array)
end
it 'returns recurring_donation_designations objects' do
expect(@recurring_donation_designations['data'].first).to be_a(Hash)
expect(@recurring_donation_designations['data'].first['id']).to_not be_nil
end
end
describe '#recurring_donation_designation', :vcr do
before do
@recurring_donation_designation = client.recurring_donation_designation(358_916, 383_099)
end
it 'returns a recurring_donation_designation object' do
expect(@recurring_donation_designation).to be_a(Hash)
expect(@recurring_donation_designation['data']['id']).to eq('383099')
end
end
end
|
MortarStone/planning_center_online-ruby
|
spec/planning_center/endpoints/people_spec.rb
|
<reponame>MortarStone/planning_center_online-ruby<filename>spec/planning_center/endpoints/people_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe PlanningCenter::Endpoints::People do
let!(:client) { FactoryBot.build(:client) }
describe '#people', :vcr do
before do
@people = client.people(per_page: 25)
end
it 'returns an array' do
expect(@people['data']).to be_an(Array)
end
it 'returns the correct number of objects' do
expect(@people['data'].count).to eq 25
end
it 'returns people objects' do
expect(@people['data'].first).to be_a(Hash)
expect(@people['data'].first['id']).to_not be_nil
end
end
describe '#people with includes', :vcr do
before do
@people = client.people(
per_page: 25,
include: %w[
households
marital_status
emails
phone_numbers
inactive_reason
addresses
name_suffix
]
)
end
it 'returns an array' do
expect(@people['data']).to be_an(Array)
end
it 'returns the correct number of objects' do
expect(@people['data'].count).to eq 25
end
it 'returns included objects' do
included = @people['included'].map { |i| i['type'] }.uniq
expect(included).to include('Household')
expect(included).to include('MaritalStatus')
expect(included).to include('Email')
expect(included).to include('PhoneNumber')
expect(included).to include('InactiveReason')
expect(included).to include('Address')
end
end
describe '#person', :vcr do
before do
@person = client.person(2_669_139)
end
it 'returns a person object' do
expect(@person).to be_a(Hash)
expect(@person['data']['id']).to eq('2669139')
end
end
end
|
MortarStone/planning_center_online-ruby
|
spec/planning_center/endpoints/funds_spec.rb
|
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe PlanningCenter::Endpoints::Funds do
let!(:client) { FactoryBot.build(:client) }
describe '#funds', :vcr do
before do
@funds = client.funds(per_page: 25)
end
it 'returns an array' do
expect(@funds['data']).to be_an(Array)
end
it 'returns the correct number of objects' do
expect(@funds['data'].count).to eq 25
end
it 'returns funds objects' do
expect(@funds['data'].first).to be_a(Hash)
expect(@funds['data'].first['id']).to_not be_nil
end
end
describe '#fund', :vcr do
before do
@fund = client.fund(131_737)
end
it 'returns a fund object' do
expect(@fund).to be_a(Hash)
expect(@fund['data']['id']).to eq('131737')
end
end
end
|
MortarStone/planning_center_online-ruby
|
lib/planning_center/client.rb
|
<gh_stars>0
# frozen_string_literal: true
require "#{File.dirname(__FILE__)}/auto_load.rb"
module PlanningCenter
class Client
include PlanningCenter::Endpoints::Addresses
include PlanningCenter::Endpoints::Campuses
include PlanningCenter::Endpoints::DesignationRefunds
include PlanningCenter::Endpoints::Donations
include PlanningCenter::Endpoints::Emails
include PlanningCenter::Endpoints::Funds
include PlanningCenter::Endpoints::Households
include PlanningCenter::Endpoints::InactiveReasons
include PlanningCenter::Endpoints::MaritalStatuses
include PlanningCenter::Endpoints::NameSuffixes
include PlanningCenter::Endpoints::People
include PlanningCenter::Endpoints::PhoneNumbers
include PlanningCenter::Endpoints::PledgeCampaigns
include PlanningCenter::Endpoints::Pledges
include PlanningCenter::Endpoints::RecurringDonationDesignations
include PlanningCenter::Endpoints::RecurringDonations
include PlanningCenter::Endpoints::Refunds
attr_accessor :url
def initialize(access_token:)
@access_token = access_token
@url = 'https://api.planningcenteronline.com'
end
private
def connection
@connection ||=
Faraday.new(url, request: { timeout: 300_000 }) do |conn|
conn.authorization :Bearer, @access_token
end
end
def get(path, params = {})
path = RequestFormatter.new(path: path, params: params).call
# puts "path = #{path}"
response = connection.get(path) do |req|
req.options.timeout = 300 # 5 minutes
end
ResponseHandler.new(response: response).call
end
end
end
|
MortarStone/planning_center_online-ruby
|
examples/households.rb
|
<reponame>MortarStone/planning_center_online-ruby<gh_stars>0
# frozen_string_literal: true
require_relative 'helper'
households = @client.households
print_households(households)
|
MortarStone/planning_center_online-ruby
|
spec/factories/clients.rb
|
<gh_stars>0
# frozen_string_literal: true
FactoryBot.define do
factory :client, class: PlanningCenter::Client do
access_token { ENV['ACCESS_TOKEN'] }
initialize_with { new(access_token: access_token) }
end
factory :invalid_client, class: PlanningCenter::Client do
access_token { 'abc' }
initialize_with { new(access_token: access_token) }
end
end
|
MortarStone/planning_center_online-ruby
|
spec/planning_center/client_spec.rb
|
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe PlanningCenter::Client do
describe '#connect', :vcr do
context 'with valid access_token' do
it 'creates a connection' do
client = FactoryBot.build(:client)
expect(client).to be_a(PlanningCenter::Client)
end
end
context 'with invalid access_token' do
it 'error on campuses', vcr: true do
client = FactoryBot.build(:invalid_client)
expect do
client.campuses
end.to raise_error(PlanningCenter::Exceptions::Unauthorized)
end
end
context 'when already connected' do
before(:all) do
@client = FactoryBot.build(:client)
end
it 'returns client' do
client = @client
expect(client).to be_a(PlanningCenter::Client)
end
end
end
end
|
MortarStone/planning_center_online-ruby
|
lib/planning_center/endpoints/emails.rb
|
# frozen_string_literal: true
module PlanningCenter
module Endpoints
module Emails
def email(id, params = {})
get(
"people/v2/emails/#{id}",
params
)
end
def emails(params = {})
# We need to order the emails by a value (created_at being the default),
# because the results are not consistently ordered without it.
get(
'people/v2/emails',
{ order: :created_at }.merge(params)
)
end
end
end
end
|
MortarStone/planning_center_online-ruby
|
examples/helpers/phone_numbers.rb
|
<gh_stars>0
# frozen_string_literal: true
def print_phone_numbers(list)
print_list('phone_number', 'id', list)
end
def print_phone_number(item)
print_item('phone_number', item)
end
def phone_number_columns
%w[
id
number
carrier
location
primary
]
end
|
MortarStone/planning_center_online-ruby
|
examples/helpers/recurring_donation_designations.rb
|
# frozen_string_literal: true
def print_recurring_donation_designations(list)
print_list('recurring_donation_designation', 'id', list)
end
def print_recurring_donation_designation(item)
print_item('recurring_donation_designation', item)
end
def recurring_donation_designation_columns
%w[
id
amount_cents
]
end
|
MortarStone/planning_center_online-ruby
|
examples/household.rb
|
<filename>examples/household.rb
# frozen_string_literal: true
require_relative 'helper'
household = @client.household(2_168_776)
print_household(household)
|
MortarStone/planning_center_online-ruby
|
examples/email.rb
|
# frozen_string_literal: true
require_relative 'helper'
email = @client.email(2_479_635)
print_email(email)
|
MortarStone/planning_center_online-ruby
|
examples/address.rb
|
<reponame>MortarStone/planning_center_online-ruby<gh_stars>0
# frozen_string_literal: true
require_relative 'helper'
address = @client.address(30_896_373)
print_address(address)
|
MortarStone/planning_center_online-ruby
|
spec/planning_center/endpoints/addresses_spec.rb
|
<reponame>MortarStone/planning_center_online-ruby
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe PlanningCenter::Endpoints::Addresses do
let!(:client) { FactoryBot.build(:client) }
describe '#addresses', :vcr do
before do
@addresses = client.addresses(per_page: 25)
end
it 'returns an array' do
expect(@addresses['data']).to be_an(Array)
end
it 'returns the correct number of objects' do
expect(@addresses['data'].count).to eq 25
end
it 'returns addresses objects' do
expect(@addresses['data'].first).to be_a(Hash)
expect(@addresses['data'].first['id']).to_not be_nil
end
end
describe '#address', :vcr do
before do
@address = client.address(30_896_373)
end
it 'returns a address object' do
expect(@address).to be_a(Hash)
expect(@address['data']['id']).to eq('30896373')
end
end
end
|
MortarStone/planning_center_online-ruby
|
lib/planning_center/request_formatter.rb
|
# frozen_string_literal: true
module PlanningCenter
class RequestFormatter
attr_accessor :path, :params
def initialize(path:, params: {})
@path = path
@params = params
end
def call
"#{path}?#{stringify_params}"
end
private
def default_params
{ per_page: 100, offset: 0 }
end
def stringify_params
arr = []
default_params.merge(params).map do |k, v|
if v.is_a?(Array)
v = v.join('%2C')
elsif is_a?(Date)
v = v.strftime('%Y-%m-%d')
end
arr << "#{k}=#{v}"
end
arr.join('&').gsub(' ', '%20')
end
end
end
|
MortarStone/planning_center_online-ruby
|
lib/planning_center/endpoints/pledge_campaigns.rb
|
# frozen_string_literal: true
module PlanningCenter
module Endpoints
module PledgeCampaigns
def pledge_campaign(id, params = {})
get(
"giving/v2/pledge_campaigns/#{id}",
params
)
end
def pledge_campaigns(params = {})
# We need to order the pledge_campaigns by a value (starts_at being the default),
# because the results are not consistently ordered without it.
get(
'giving/v2/pledge_campaigns',
{ order: :starts_at }.merge(params)
)
end
end
end
end
|
MortarStone/planning_center_online-ruby
|
lib/planning_center/endpoints/refunds.rb
|
<reponame>MortarStone/planning_center_online-ruby<filename>lib/planning_center/endpoints/refunds.rb
# frozen_string_literal: true
module PlanningCenter
module Endpoints
module Refunds
def refund(donation_id, params = {})
# There is only one refund per donation and the refund can only be accessed
# through the donation
get(
"giving/v2/donations/#{donation_id}/refund",
params
)
end
end
end
end
|
MortarStone/planning_center_online-ruby
|
examples/helpers/campuses.rb
|
# frozen_string_literal: true
def print_campuses(list)
print_list('campus', 'id', list)
end
def print_campus(item)
print_item('campus', item)
end
def campus_columns
%w[
id
name
]
end
|
MortarStone/planning_center_online-ruby
|
examples/recurring_donation_designations.rb
|
# frozen_string_literal: true
require_relative 'helper'
recurring_donation_designations = @client.recurring_donation_designations(358_916)
print_recurring_donation_designations(recurring_donation_designations)
|
MortarStone/planning_center_online-ruby
|
examples/helpers/recurring_donations.rb
|
<reponame>MortarStone/planning_center_online-ruby
# frozen_string_literal: true
def print_recurring_donations(list)
print_list('recurring_donation', 'id', list)
end
def print_recurring_donation(item)
print_item('recurring_donation', item)
end
def recurring_donation_columns
%w[
id
amount_cents
status
last_donation_received_at
next_occurrence
]
end
|
MortarStone/planning_center_online-ruby
|
examples/helpers/donations.rb
|
# frozen_string_literal: true
def print_donations(list)
print_list('donation', 'id', list)
end
def print_donation(item)
print_item('donation', item)
end
def donation_columns
%w[
id
amount_cents
received_at
]
end
|
MortarStone/planning_center_online-ruby
|
spec/planning_center/endpoints/designation_refunds_spec.rb
|
<filename>spec/planning_center/endpoints/designation_refunds_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe PlanningCenter::Endpoints::DesignationRefunds do
let!(:client) { FactoryBot.build(:client) }
describe '#designation_refunds', :vcr do
before do
@designation_refunds = client.designation_refunds(53_134_447)
end
it 'returns an array' do
expect(@designation_refunds['data']).to be_an(Array)
end
it 'returns designation_refunds objects' do
expect(@designation_refunds['data'].first).to be_a(Hash)
expect(@designation_refunds['data'].first['id']).to_not be_nil
end
end
end
|
MortarStone/planning_center_online-ruby
|
examples/person.rb
|
# frozen_string_literal: true
require_relative 'helper'
person = @client.person(2_669_139)
print_person(person)
|
MortarStone/planning_center_online-ruby
|
lib/planning_center/endpoints/recurring_donation_designations.rb
|
<filename>lib/planning_center/endpoints/recurring_donation_designations.rb
# frozen_string_literal: true
module PlanningCenter
module Endpoints
module RecurringDonationDesignations
def recurring_donation_designation(donation_id, id, params = {})
get(
"giving/v2/recurring_donations/#{donation_id}/designations/#{id}",
params
)
end
def recurring_donation_designations(donation_id, params = {})
get(
"giving/v2/recurring_donations/#{donation_id}/designations",
params
)
end
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.