repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/spec/highrise/comment_spec.rb | spec/highrise/comment_spec.rb | require 'spec_helper'
describe Highrise::Comment do
it { should be_a_kind_of Highrise::Base }
end
| ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/spec/highrise/user_spec.rb | spec/highrise/user_spec.rb | require 'spec_helper'
describe Highrise::User do
it { should be_a_kind_of Highrise::Base }
it ".me" do
Highrise::User.should_receive(:find).with(:one, {:from => "/me.xml"}).and_return(subject)
Highrise::User.me.should == subject
end
it "#join" do
group_mock = mock("group")
group_mock.should_receive(:id).and_return(2)
subject.should_receive(:id).and_return(1)
Highrise::Membership.should_receive(:create).with({:user_id=>1, :group_id=>2})
subject.join(group_mock)
end
end
| ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/spec/highrise/note_spec.rb | spec/highrise/note_spec.rb | require 'spec_helper'
describe Highrise::Note do
subject { Highrise::Note.new(:id => 1) }
it { should be_a_kind_of Highrise::Base }
it_should_behave_like "a paginated class"
it "#comments" do
Highrise::Comment.should_receive(:find).with(:all, {:from=>"/notes/1/comments.xml"}).and_return("comments")
subject.comments.should == "comments"
end
end
| ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/spec/highrise/subject_data_spec.rb | spec/highrise/subject_data_spec.rb | require 'spec_helper'
describe Highrise::SubjectData do
it { should be_a_kind_of Highrise::Base }
it "Two different subject datas with different values are not equal" do
martini = Highrise::SubjectData.new({:id => 1, :value => "Martini", :subject_field_id => 3, :subject_field_label => "Cocktail"})
sling = Highrise::SubjectData.new({:id => 2, :value => "Singapore Sling", :subject_field_id => 4, :subject_field_label => "Cocktail"})
martini.should_not==sling
end
it "Two different subject datas with different labels are not equal" do
martini = Highrise::SubjectData.new({:id => 1, :value => "Martini", :subject_field_id => 3, :subject_field_label => "Cocktail"})
sling = Highrise::SubjectData.new({:id => 2, :value => "Martini", :subject_field_id => 4, :subject_field_label => "Vermouth Brands"})
martini.should_not==sling
end
it "Two the same subject datas are equal" do
martini = Highrise::SubjectData.new({:id => 1, :value => "Martini", :subject_field_id => 3, :subject_field_label => "Cocktail"})
another_martini = Highrise::SubjectData.new({:id => 2, :value => "Martini", :subject_field_id => 4, :subject_field_label => "Cocktail"})
martini.should==another_martini
end
end | ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/examples/extending.rb | examples/extending.rb | #
# Example of extending a class when you need to synthesize an attribute.
#
# Adds Highrise::Person.{phone,fax,email} to the Person class inside your
# module
#
module MyModule
include Highrise
Highrise::Person.class_eval do
class << self
def lookup(id, list, item, location)
module_eval <<-EOT
def #{id}
contact_data.#{list}.each do |i|
return i.#{item}.strip if i.location == "#{location}"
end
''
end
EOT
end
private :lookup
end
lookup(:phone, 'phone_numbers', 'number', 'Work')
lookup(:fax, 'phone_numbers', 'number', 'Fax')
lookup(:email, 'email_addresses', 'address', 'Work')
end
end | ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/examples/sample.rb | examples/sample.rb | require 'highrise'
require 'pp'
Highrise::Base.site = 'https://yoursite.highrisehq.com'
Highrise::Base.user = 'xxx'
@tags = Highrise::Tag.find(:all)
pp @tags | ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/examples/config_initializers_highrise.rb | examples/config_initializers_highrise.rb | if Rails.env != 'test' then
Highrise::Base.site = 'https://example.com.i'
Highrise::Base.user = 'my_fancy_auth_token'
end | ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/lib/highrise.rb | lib/highrise.rb | require 'highrise/base'
require 'highrise/pagination'
require 'highrise/taggable'
require 'highrise/searchable'
require 'highrise/custom_fields'
require 'highrise/subject'
require 'highrise/comment'
require 'highrise/company'
require 'highrise/email'
require 'highrise/group'
require 'highrise/kase'
require 'highrise/membership'
require 'highrise/note'
require 'highrise/person'
require 'highrise/task'
require 'highrise/user'
require 'highrise/tag'
require 'highrise/deal'
require 'highrise/account'
require 'highrise/deal_category'
require 'highrise/task_category'
require 'highrise/party'
require 'highrise/recording'
require 'highrise/subject_data'
require 'highrise/subject_field'
| ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/lib/highrise/tag.rb | lib/highrise/tag.rb | module Highrise
class Tag < Base
def ==(object)
(object.instance_of?(self.class) && object.id == self.id && object.name == self.name)
end
end
end | ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/lib/highrise/task.rb | lib/highrise/task.rb | module Highrise
class Task < Base
# find(:all, :from => :upcoming)
# find(:all, :from => :assigned)
# find(:all, :from => :completed)
def complete!
load_attributes_from_response(post(:complete))
end
end
end | ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/lib/highrise/version.rb | lib/highrise/version.rb | module Highrise
VERSION = "3.2.3"
end | ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/lib/highrise/membership.rb | lib/highrise/membership.rb | module Highrise
class Membership < Base; end
end | ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/lib/highrise/group.rb | lib/highrise/group.rb | module Highrise
class Group < Base; end
end | ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/lib/highrise/searchable.rb | lib/highrise/searchable.rb | module Highrise
module Searchable
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
# List By Search Criteria
# Ex: Highrise::Person.search(:email => "john.doe@example.com", :country => "CA")
# Available criteria are: city, state, country, zip, phone, email
def search(options = {})
search_params = options.inject({}) { |h, (k, v)| h["criteria[#{k}]"] = v; h }
# This might have to be changed in the future if other non-pagable resources become searchable
if self.respond_to?(:find_all_across_pages)
self.find_all_across_pages(:from => "/#{self.collection_name}/search.xml", :params => search_params)
else
self.find(:all, {:from => "/#{self.collection_name}/search.xml", :params => search_params})
end
end
end
end
end | ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/lib/highrise/account.rb | lib/highrise/account.rb | module Highrise
class Account < Base
def self.me
find(:one, :from => "/account.xml")
end
end
end | ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/lib/highrise/recording.rb | lib/highrise/recording.rb | module Highrise
class Recording < Base
include Pagination
end
end | ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/lib/highrise/custom_fields.rb | lib/highrise/custom_fields.rb | module Highrise
module CustomFields
def field(field_label)
custom_fields = attributes["subject_datas"] ||= []
field = custom_fields.detect do |field|
field.subject_field_label == field_label
end
field ? field.value : nil
end
def new_subject_data(field, value)
Highrise::SubjectData.new(:subject_field_id => field.id, :subject_field_label => field.label, :value => value)
end
def set_field_value(field_label, new_value)
custom_fields = attributes["subject_datas"] ||= []
custom_fields.each do |field|
return field.value = new_value if field.subject_field_label == field_label
end
SubjectField.find(:all).each do |custom_field|
if custom_field.label == field_label
return attributes["subject_datas"] << new_subject_data(custom_field, new_value)
end
end
end
def transform_subject_field_label field_label
field_label.downcase.tr(' ', '_')
end
def convert_method_to_field_label method
custom_fields = attributes["subject_datas"] ||= []
custom_fields.each do |field|
method_name_from_field = transform_subject_field_label(field.subject_field_label)
return field if method_name_from_field == method
end
nil
end
def method_missing(method_symbol, *args)
method_name = method_symbol.to_s
if method_name[-1,1] == "="
attribute_name = method_name[0...-1]
field = convert_method_to_field_label(attribute_name)
return set_field_value(field.subject_field_label, args[0]) if field
return super if attributes[attribute_name]
subject_fields = SubjectField.find(:all)
unless subject_fields.nil?
subject_fields.each do |custom_field|
if transform_subject_field_label(custom_field.label) == attribute_name
return attributes["subject_datas"] << new_subject_data(custom_field, args[0])
end
end
end
else
field = convert_method_to_field_label(method_name)
return field(field.subject_field_label) if field
end
super
end
end
end
| ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/lib/highrise/task_category.rb | lib/highrise/task_category.rb | module Highrise
class TaskCategory < Base; end
end | ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/lib/highrise/pagination.rb | lib/highrise/pagination.rb | module Highrise
module Pagination
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def find_all_across_pages(options = {})
records = []
each(options) { |record| records << record }
records
end
# This only is usefull for company, person & recordings, but should be safely ignored by other classes
def find_all_across_pages_since(time)
find_all_across_pages(:params => { :since => time.utc.strftime("%Y%m%d%H%M%S") })
end
# This is useful only for Company, Person, Note, Comment, Email and Task, but should be safely ignored by other classes
def find_all_deletions_across_pages(options = {})
# point to the global deletions feed
options[:from] = '/deletions.xml'
records = []
each_deletions(options) { |record| records << record }
records
end
# This is useful only for Company, Person, Note, Comment, Email and Task, but should be safely ignored by other classes
def find_all_deletions_across_pages_since(time)
find_all_deletions_across_pages(:params => { :since => time.utc.strftime("%Y%m%d%H%M%S") })
end
private
def each(options = {})
options[:params] ||= {}
options[:params][:n] = 0
loop do
if (records = self.find(:all, options)).try(:any?)
records.each { |record| yield record }
options[:params][:n] += records.size
else
break # no people included on that page, thus no more people total
end
end
end
def each_deletions(options = {})
options[:params] ||= {}
# first index for deletions is 1
options[:params][:n] = 1
loop do
if (records = self.find(:all, options)).try(:any?)
# reject the records whose resource type is different from self
records.reject!{|r| r.class.to_s.split('::').last != self.to_s.split('::').last}
records.each{ |record| yield record }
# index increment for deletions is 1 per page of 500 resources
options[:params][:n] += 1
else
break # no deletions included on that page, thus no more deletions
end
end
end
end
end
end
| ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/lib/highrise/email.rb | lib/highrise/email.rb | module Highrise
class Email < Base
include Pagination
def comments
Comment.find(:all, :from => "/emails/#{id}/comments.xml")
end
end
end | ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/lib/highrise/comment.rb | lib/highrise/comment.rb | module Highrise
class Comment < Base; end
end | ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/lib/highrise/base.rb | lib/highrise/base.rb | require 'active_resource'
module Highrise
class Base < ActiveResource::Base
protected
class << self
# If headers are not defined in a given subclass, then obtain
# headers from the superclass.
# http://opensoul.org/blog/archives/2010/02/16/active-resource-in-practice/
def headers
if defined?(@headers)
@headers
elsif superclass != Object && superclass.headers
superclass.headers
else
@headers ||= {}
end
end
def oauth_token=(token)
headers['Authorization'] = "Bearer #{token}"
end
end
# Fix for ActiveResource 3.1+ errors
self.format = :xml
# Dynamic finder for attributes
def self.method_missing(method, *args)
if method.to_s =~ /^find_(all_)?by_([_a-zA-Z]\w*)$/
raise ArgumentError, "Dynamic finder method must take an argument." if args.empty?
options = args.extract_options!
resources = respond_to?(:find_all_across_pages) ? send(:find_all_across_pages, options) : send(:find, :all)
resources.send($1 == 'all_' ? 'select' : 'detect') { |container| container.send($2) == args.first }
else
super
end
end
end
end
| ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/lib/highrise/note.rb | lib/highrise/note.rb | module Highrise
class Note < Base
include Pagination
def comments
Comment.find(:all, :from => "/notes/#{id}/comments.xml")
end
end
end | ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/lib/highrise/kase.rb | lib/highrise/kase.rb | module Highrise
class Kase < Subject
include Pagination
def open!
update_attribute(:closed_at, nil)
end
def close!
update_attribute(:closed_at, Time.now.utc)
end
def self.open
Kase.find(:all, :from => "/kases/open.xml")
end
def self.closed
Kase.find(:all, :from => "/kases/closed.xml")
end
def self.all_open_across_pages
find_all_across_pages(:from => "/kases/open.xml")
end
def self.all_closed_across_pages
find_all_across_pages(:from => "/kases/closed.xml")
end
end
end
| ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/lib/highrise/party.rb | lib/highrise/party.rb | module Highrise
class Party < Base
def self.recently_viewed
find(:all, :from => "/parties/recently_viewed.xml")
end
def self.deletions_since(time)
find(:all, :from => "/parties/deletions.xml", :params => { :since => time.utc.strftime("%Y%m%d%H%M%S") })
end
end
end | ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/lib/highrise/taggable.rb | lib/highrise/taggable.rb | module Highrise
module Taggable
def tags
unless self.attributes.has_key?("tags")
person_or_company = self.class.find(id)
self.attributes["tags"] = person_or_company.attributes.has_key?("tags") ? person_or_company.tags : []
end
self.attributes["tags"]
end
def tag!(tag_name)
self.post(:tags, :name => tag_name) unless tag_name.blank?
end
def untag!(tag_name)
to_delete = self.tags.find{|tag| tag.attributes['name'] == tag_name} unless tag_name.blank?
self.untag_id!(to_delete.attributes['id']) unless to_delete.nil?
end
protected
def untag_id!(tag_id)
self.delete("tags/#{tag_id}")
end
end
end
| ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/lib/highrise/subject.rb | lib/highrise/subject.rb | module Highrise
class Subject < Base
def notes(options={})
options.merge!(:from => "/#{self.class.collection_name}/#{id}/notes.xml")
Note.find_all_across_pages(options)
end
def add_note(attrs={})
attrs[:subject_id] = self.id
attrs[:subject_type] = self.label
Note.create attrs
end
def add_task(attrs={})
attrs[:subject_id] = self.id
attrs[:subject_type] = self.label
Task.create attrs
end
def emails(options={})
options.merge!(:from => "/#{self.class.collection_name}/#{id}/emails.xml")
Email.find_all_across_pages(options)
end
def upcoming_tasks(options={})
options.merge!(:from => "/#{self.class.collection_name}/#{id}/tasks.xml")
Task.find(:all, options)
end
def label
self.class.name.split('::').last
end
end
end | ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/lib/highrise/person.rb | lib/highrise/person.rb | module Highrise
class Person < Subject
include Pagination
include Taggable
include Searchable
include CustomFields
def company
Company.find(company_id) if company_id
end
def name
"#{first_name rescue ''} #{last_name rescue ''}".strip
end
def address
contact_data.addresses.first
end
def web_address
contact_data.web_addresses.first
end
def email_addresses
contact_data.email_addresses.collect { |address| address.address } rescue []
end
def phone_numbers
contact_data.phone_numbers.collect { |phone_number| phone_number.number } rescue []
end
def label
'Party'
end
end
end
| ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/lib/highrise/subject_field.rb | lib/highrise/subject_field.rb | module Highrise
class SubjectField < Base
def initialize(attributes = {}, persisted = false)
super
@use_cache = false
end
def self.use_cache(use_cache = true)
@use_cache = use_cache
end
def self.find_every(options)
if @use_cache
@subject_field_cache ||= super
else
super
end
end
def self.invalidate_cache
@subject_field_cache = nil
end
end
end
| ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/lib/highrise/deal.rb | lib/highrise/deal.rb | module Highrise
class Deal < Subject
include Pagination
def update_status(status)
raise ArgumentError, "status must be one of 'pending', 'won', or 'lost'" unless %w[pending won lost].include?(status)
self.put(:status, :status => {:name => status})
end
end
end
| ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/lib/highrise/subject_data.rb | lib/highrise/subject_data.rb | module Highrise
class SubjectData < Base
def==other
attributes["value"] == other.attributes["value"] &&
attributes["subject_field_label"] == other.attributes["subject_field_label"]
end
end
end | ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/lib/highrise/deal_category.rb | lib/highrise/deal_category.rb | module Highrise
class DealCategory < Base; end
end | ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/lib/highrise/company.rb | lib/highrise/company.rb | module Highrise
class Company < Subject
include Pagination
include Taggable
include Searchable
include CustomFields
def people
Person.find_all_across_pages(:from => "/companies/#{id}/people.xml")
end
def label
'Party'
end
end
end | ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/lib/highrise/user.rb | lib/highrise/user.rb | module Highrise
class User < Base
def join(group)
Membership.create(:user_id => id, :group_id => group.id)
end
# Permits API-key retrieval using name and password.
# Highrise::User.site = "https://yourcompany.highrise.com"
# Highrise::User.user = "your_user_name"
# Highrise::User.password = "s3kr3t"
# Highrise::User.me.token # contains the API token for "your_user_name"
def self.me
user = User.new()
find(:one, :from => "/me.xml")
end
end
end | ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
sensu/sensu-ansible | https://github.com/sensu/sensu-ansible/blob/94d7a004970bf67c8673b0feb98b3a8cdfc63bd9/molecule/shared/tests/test_default.rb | molecule/shared/tests/test_default.rb | # Verify that redis, rabbitmq-server, sensu-{api,client}, and Uchiwa
# are all listening as expected
# frozen_string_literal: true
# Redis
describe port(6379) do
it { should be_listening }
its('protocols') { should include 'tcp' }
its('addresses') { should be_in ['0.0.0.0'] }
end
# RabbitMQ Server
describe port(5671) do
it { should be_listening }
its('protocols') { should include 'tcp' }
its('addresses') { should be_in ['0.0.0.0', '::', '[::]'] }
end
# Sensu API
describe port(4567) do
it { should be_listening }
its('protocols') { should include 'tcp' }
its('addresses') { should be_in ['0.0.0.0'] }
end
# Sensu Client TCP/UDP Socket
describe port(3030) do
it { should be_listening }
its('protocols') { should include 'tcp' }
# Broken on 14.04 - its('protocols') { should include 'udp' }
its('addresses') { should include '127.0.0.1' }
end
# Sensu Client HTTP Socket
describe port(3031) do
it { should be_listening }
its('protocols') { should include 'tcp' }
its('addresses') { should include '127.0.0.1' }
end
# Uchiwa
describe port(3000) do
it { should be_listening }
its('protocols') { should include 'tcp' }
its('addresses') { should be_in ['0.0.0.0', '::', '[::]'] }
end
# Ensure Sensu API has one consumer
describe http('http://127.0.0.1:4567/health',
auth: { user: 'admin', pass: 'secret' },
params: { consumers: 1 }) do
its('status') { should eq 204 }
end
# Ensure disk check exists
describe json('/etc/sensu/conf.d/sensu_masters/check_disk_usage.json') do
its(%w[checks check_disk_usage command]) \
{ should eq 'check-disk-usage.rb' }
its(%w[checks check_disk_usage interval]) { should eq 120 }
end
# Ensure disk metrics exists
describe json('/etc/sensu/conf.d/sensu_checks/metrics_disk_usage.json') do
its(%w[checks metrics_disk_usage command]) \
{ should eq 'metrics-disk-usage.rb' }
its(%w[checks metrics_disk_usage interval]) { should eq 60 }
end
# Ensure not_used does not exist
describe file('/etc/sensu/conf.d/not_used/not_a_check.json') do
it { should_not exist }
end
| ruby | MIT | 94d7a004970bf67c8673b0feb98b3a8cdfc63bd9 | 2026-01-04T17:54:41.726534Z | false |
trunkclub/faceted | https://github.com/trunkclub/faceted/blob/b9a6822024f63f7b48b5fcdb601b4f06f17abbb3/spec/collector_spec.rb | spec/collector_spec.rb | require 'spec_helper'
class Musician # Mock AR model
attr_accessor :id, :name, :rating, :errors, :birthplace_id
def initialize(params={}); params.each{|k,v| self.send("#{k}=",v) if self.respond_to?(k)}; end
def attributes; {:id => self.id, :name => self.name, :rating => self.rating}; end
end
class Birthplace # Mock AR model
attr_accessor :id, :city, :state
def initialize(params={}); params.each{|k,v| self.send("#{k}=",v) if self.respond_to?(k)}; end
def attributes; {:id => self.id, :city => self.city, :state => self.state}; end
end
class Song # Mock AR model
attr_accessor :id, :title, :rating
def initialize(params={}); params.each{|k,v| self.send("#{k}=",v) if self.respond_to?(k)}; end
def attributes; {:id => self.id, :title => self.title}; end
end
module MyApi
class Birthplace
include Faceted::Presenter
presents :birthplace
field :city
field :state
end
class Musician
include Faceted::Presenter
presents :musician
field :name
field :rating
field :birthplace_id
end
class Song
include Faceted::Presenter
presents :song
field :title
field :rating
end
class Band
include Faceted::Collector
collects :musicians, :find_by => :birthplace_id
collects :songs
end
describe Band do
it 'creates an accessor method for its collected objects' do
Band.new.respond_to?(:musicians).should be_true
Band.new.respond_to?(:songs).should be_true
end
describe 'with associated objects' do
it 'initializes the associated objects in the correct namespace' do
band = MyApi::Band.new(:birthplace_id => 1)
band.stub(:id) { 3 }
MyApi::Musician.stub(:where) { [MyApi::Musician.new] }
MyApi::Song.stub(:where) { [MyApi::Song.new] }
MyApi::Song.should_receive(:where).with('band_id' => 3)
band.musicians.first.class.name.should == "MyApi::Musician"
band.songs.first.class.name.should == "MyApi::Song"
end
end
end
end
| ruby | MIT | b9a6822024f63f7b48b5fcdb601b4f06f17abbb3 | 2026-01-04T17:54:46.250539Z | false |
trunkclub/faceted | https://github.com/trunkclub/faceted/blob/b9a6822024f63f7b48b5fcdb601b4f06f17abbb3/spec/controller_spec.rb | spec/controller_spec.rb | require 'spec_helper'
class Birthplace # Mock AR model
attr_accessor :id, :city, :state
def initialize(params={}); params.each{|k,v| self.send("#{k}=",v) if self.respond_to?(k)}; end
def attributes; {:id => self.id, :city => self.city, :state => self.state}; end
def reload; self; end
end
module MyApi
class MyApi::Application < Rails::Application
end
class Birthplace
include Faceted::Presenter
presents :birthplace
field :city
field :state
end
class BirthplacesController < ActionController::Base
include Faceted::Controller
include Rails.application.routes.url_helpers
def show
@birthplace = MyApi::Birthplace.first
render_response @birthplace
end
end
end
describe MyApi::BirthplacesController, :type => :controller do
before do
MyApi::Birthplace.stub(:first) { MyApi::Birthplace.new }
MyApi::Application.routes.draw do
namespace :my_api do
resources :birthplaces
end
end
end
it 'renders with a 200 when the operation is successful' do
MyApi::Birthplace.any_instance.stub(:success) { true }
get :show, :id => 1
response.code.should == "200"
end
it 'renders with a 400 when the operation is unsuccessful' do
MyApi::Birthplace.any_instance.stub(:success) { false }
get :show, :id => 1
response.code.should == "400"
end
end
| ruby | MIT | b9a6822024f63f7b48b5fcdb601b4f06f17abbb3 | 2026-01-04T17:54:46.250539Z | false |
trunkclub/faceted | https://github.com/trunkclub/faceted/blob/b9a6822024f63f7b48b5fcdb601b4f06f17abbb3/spec/presenter_spec.rb | spec/presenter_spec.rb | require 'spec_helper'
class Musician # pretend that this is an AR model
attr_accessor :id, :name, :rating, :errors, :birthplace_id, :alive
def initialize(params={}); params.each{|k,v| self.send("#{k}=",v) if self.respond_to?(k)}; end
def attributes; {:id => self.id, :name => self.name, :rating => self.rating, :alive => self.alive}; end
def reload; self; end
end
class Birthplace # another make-believe AR model
attr_accessor :id, :city, :state
def initialize(params={}); params.each{|k,v| self.send("#{k}=",v) if self.respond_to?(k)}; end
def attributes; {:id => self.id, :city => self.city, :state => self.state}; end
def reload; self; end
end
class Album # and yet another make-believe AR model
attr_accessor :id, :name
def initialize(params={}); params.each{|k,v| self.send("#{k}=",v) if self.respond_to?(k)}; end
def attributes; {:id => self.id, :name => self.name}; end
def reload; self; end
end
class AlbumTrack
attr_accessor :id, :title
def initialize(params={}); params.each{|k,v| self.send("#{k}=",v) if self.respond_to?(k)}; end
def attributes; {:id => self.id, :title => self.name}; end
def reload; self; end
end
module MyApi
class Birthplace
include Faceted::Presenter
presents :birthplace
field :city
field :state
end
class Musician
include Faceted::Presenter
presents :musician
field :name
field :rating
field :birthplace_id
field :alive
end
class Album
include Faceted::Presenter
presents :album, :find_by => :name
field :name
end
class AlbumTrack
include Faceted::Presenter
presents :album_track
field :title
end
describe Musician do
before do
@ar_musician = ::Musician.new(:id => 1, :name => 'Johnny Cash', :rating => 'Good', :alive => false)
::Musician.stub(:where) { [@ar_musician] }
@ar_birthplace = ::Birthplace.new(:id => 1, :city => 'Kingsland', :state => 'Arkansas')
::Birthplace.stub(:where) { [@ar_birthplace] }
end
describe 'initialized with an instantiated object' do
let(:musician_presenter) { MyApi::Musician.from(@ar_musician) }
it 'accepts an object' do
musician_presenter.send(:object).should == @ar_musician
end
it 'initializes with the attributes of the object' do
musician_presenter.name.should == 'Johnny Cash'
end
end
describe 'initialized with a presented object' do
describe 'inherits values from its AR counterpart' do
it 'normal values' do
musician = MyApi::Musician.new(:id => 1)
musician.name.should == 'Johnny Cash'
end
it 'boolean values' do
musician = MyApi::Musician.new(:id => 1)
musician.alive.should be_false
musician.alive.should_not be_nil
end
it 'excludes fields' do
musician = MyApi::Musician.new(:id => 1, :excludes => [:rating])
musician.schema_fields.include?(:rating).should be_false
end
it 'excludes relations' do
musician = MyApi::Musician.new(:id => 1, :excludes => [:birthplace])
musician.schema_fields.include?(:birthplace).should be_false
end
end
it 'overwrites values from its AR counterpart' do
musician = MyApi::Musician.new(:id => 1, :rating => 'Great')
musician.rating.should == 'Great'
end
describe 'saves its counterpart' do
it 'successfully' do
musician = MyApi::Musician.new(:id => 1)
@ar_musician.should_receive(:save) { true }
musician.save.should be_true
end
it 'handling failure' do
musician = MyApi::Musician.new(:id => 1)
@ar_musician.should_receive(:save) { false }
musician.save.should be_false
end
it 'failing and populating its errors' do
musician = MyApi::Musician.new(:id => 1)
@ar_musician.should_receive(:save) { false }
@ar_musician.stub_chain(:errors, :full_messages) { ["Something went wrong", "Terribly wrong"] }
musician.save
musician.errors.count.should == 2
musician.errors.last.should == "Terribly wrong"
end
end
end
describe 'with an associated object' do
it 'initializes the associated object in the correct namespace' do
musician = MyApi::Musician.new(:id => 1, :birthplace_id => 1)
musician.birthplace.city.should == 'Kingsland'
end
it 'initializes the associated object finding by a specified key' do
@ar_album = ::Album.new(:id => 1, :name => 'Greatest Hits')
::Album.stub(:where) { [@ar_album] }
album = MyApi::Album.new(:name => 'Greatest Hits')
album.id.should == 1
end
it 'does not choke on associated objects with underscores in their names' do
@ar_album_track = ::AlbumTrack.new(:id => 1, :title => 'The Gambler')
::AlbumTrack.stub(:where) { [@ar_album_track] }
track = MyApi::AlbumTrack.new(:id => 1)
track.album_track.should == @ar_album_track
end
end
end
end
| ruby | MIT | b9a6822024f63f7b48b5fcdb601b4f06f17abbb3 | 2026-01-04T17:54:46.250539Z | false |
trunkclub/faceted | https://github.com/trunkclub/faceted/blob/b9a6822024f63f7b48b5fcdb601b4f06f17abbb3/spec/spec_helper.rb | spec/spec_helper.rb | require 'rubygems'
require 'active_model'
require 'active_support'
require 'bundler/setup'
require 'faceted'
require 'rails/all'
require 'rspec'
require 'rspec/rails' | ruby | MIT | b9a6822024f63f7b48b5fcdb601b4f06f17abbb3 | 2026-01-04T17:54:46.250539Z | false |
trunkclub/faceted | https://github.com/trunkclub/faceted/blob/b9a6822024f63f7b48b5fcdb601b4f06f17abbb3/lib/faceted.rb | lib/faceted.rb | module Faceted
require 'faceted/model'
require 'faceted/has_object'
require 'faceted/collector'
require 'faceted/controller'
require 'faceted/presenter'
end | ruby | MIT | b9a6822024f63f7b48b5fcdb601b4f06f17abbb3 | 2026-01-04T17:54:46.250539Z | false |
trunkclub/faceted | https://github.com/trunkclub/faceted/blob/b9a6822024f63f7b48b5fcdb601b4f06f17abbb3/lib/faceted/presenter.rb | lib/faceted/presenter.rb | module Faceted
module Presenter
include Faceted::HasObject
# Class methods ===========================================================
def self.included(base)
base.extend ActiveModel::Naming
base.extend ClassMethods
base.extend Faceted::Model::ModelClassMethods
base.send(:attr_accessor, :id)
base.send(:attr_accessor, :errors)
base.send(:attr_accessor, :success)
end
module ClassMethods
def klass
@presents
end
def presents(name, args={})
class_name = args[:class_name] || name.to_s.classify # LineItem
@presents = eval(class_name)
define_method :find_by do
args[:find_by] || :id
end
define_method :"#{name}" do
object
end
end
def all
materialize(klass.all)
end
def find(id)
materialize(klass.where(id: id)).first
end
def where(args)
if klass.respond_to? :fields
if klass.fields.respond_to?(:keys)
# Mongoid
attrs = args.select{|k,v| klass.fields.keys.include? k.to_s}
else
attrs = args.select{|k,v| klass.fields.include? k.to_s}
end
else
# ActiveRecord et al
attrs = args.select{|k,v| klass.column_names.include? k.to_s}
end
materialize(klass.where(attrs))
end
end
end
end
| ruby | MIT | b9a6822024f63f7b48b5fcdb601b4f06f17abbb3 | 2026-01-04T17:54:46.250539Z | false |
trunkclub/faceted | https://github.com/trunkclub/faceted/blob/b9a6822024f63f7b48b5fcdb601b4f06f17abbb3/lib/faceted/collector.rb | lib/faceted/collector.rb | module Faceted
module Collector
include Faceted::Model
def self.included(base)
base.extend ActiveModel::Naming
base.send(:attr_accessor, :errors)
base.send(:attr_accessor, :success)
base.send(:attr_accessor, :fields)
base.extend ClassMethods
base.extend Faceted::Model::ModelClassMethods
end
# Class methods ===========================================================
module ClassMethods
def collects(name, args={})
@fields = [name]
find_by = args[:find_by] ? args[:find_by] : "#{self.name.split('::')[-1].underscore.singularize}_id"
@collects ||= {}
@collects[name.downcase] = eval "#{scope}#{args[:class_name] || name.to_s.classify}"
define_method :"#{name.downcase}" do
objects(name.downcase.to_sym)
end
if args[:find_by].nil?
define_method :"#{name.downcase}_finder" do
{"#{find_by}" => self.id}
end
else
define_method :"#{name.downcase}_finder" do
{"#{find_by}" => self.send(find_by)}
end
end
self.send(:attr_accessor, find_by)
end
def collected_classes
@collects
end
end
# Instance methods =========================================================
def initialize(args={})
! args.empty? && args.symbolize_keys.delete_if{|k,v| v.nil?}.each do |k,v|
self.send("#{k}=", v) if self.respond_to?("#{k}=") && ! v.blank?
end
self.errors = []
self.success = true
end
def to_hash
self.class.fields.inject({}){ |h,f| h[f] = self.send(f).map{|o| o.to_hash}; h }
end
private
def objects(klass)
return [] unless self.class.collected_classes
return [] unless self.class.collected_classes.keys.include?(klass)
self.class.collected_classes[klass].where(self.send("#{klass.to_s}_finder"))
end
end
end | ruby | MIT | b9a6822024f63f7b48b5fcdb601b4f06f17abbb3 | 2026-01-04T17:54:46.250539Z | false |
trunkclub/faceted | https://github.com/trunkclub/faceted/blob/b9a6822024f63f7b48b5fcdb601b4f06f17abbb3/lib/faceted/interface.rb | lib/faceted/interface.rb | module Faceted
module Interface
include Faceted::HasObject
# Class methods ===========================================================
def self.included(base)
base.extend ActiveModel::Naming
base.extend ClassMethods
base.extend Faceted::Model::ModelClassMethods
base.send(:attr_accessor, :id)
base.send(:attr_accessor, :errors)
end
module ClassMethods
def klass
@wraps
end
def wraps(name, args={})
class_name = args[:class_name] || name.to_s.classify
@wraps = eval(class_name)
define_method :"#{class_name.downcase}" do
object
end
end
def where(args)
materialize(klass.where(args))
end
end
end
end
| ruby | MIT | b9a6822024f63f7b48b5fcdb601b4f06f17abbb3 | 2026-01-04T17:54:46.250539Z | false |
trunkclub/faceted | https://github.com/trunkclub/faceted/blob/b9a6822024f63f7b48b5fcdb601b4f06f17abbb3/lib/faceted/has_object.rb | lib/faceted/has_object.rb | module Faceted
module HasObject
module ClassMethods
def fields
@fields ||= [:id]
end
def materialize(objects=[])
objects.compact.inject([]) do |a, object|
instance = self.new
instance.send(:object=, object)
instance.send(:initialize_with_object)
a << instance
end
end
end
# Instance methods =======================================================
def initialize(args={})
self.excludes = args.delete('excludes') || args.delete(:excludes)
unless args.empty?
self.id = args[:id]
args.symbolize_keys.delete_if{|k,v| v.nil?}.each{|k,v| self.send("#{k}=", v) if self.respond_to?("#{k}=") && ! v.nil? }
initialize_with_object
args.symbolize_keys.delete_if{|k,v| v.nil?}.each{|k,v| self.send("#{k}=", v) if self.respond_to?("#{k}=") && ! v.nil? }
end
self.errors = []
self.success = true
end
def delete
self.success = object.delete
end
def excludes=(value)
@excludes = value.nil? ? [] : value.map(&:to_sym)
end
def excludes
@excludes ||= []
end
def reinitialize_with_object(obj)
obj.reload
schema_fields.each{ |k| self.send("#{k}=", obj.send(k)) if obj.respond_to?(k) && self.send(:settable_field?, k) }
end
def save
return false unless schema_fields.present?
schema_fields.each{ |k| self.send(:object).send("#{k}=", self.send(k)) if self.send(:settable_field?, k) }
self.success = object.save
self.errors = object.errors && object.errors.full_messages
self.reinitialize_with_object(object) if self.success
self.success
end
def schema_fields
self.class.fields - self.excludes - [:excludes]
end
def to_hash
schema_fields.inject({}) {|h,k| h[k] = self.send(k) if self.respond_to?(k); h}
end
private
def initialize_with_object
return unless object
schema_fields.each{|k| self.send("#{k}=", object.send(k)) if object.respond_to?(k) && self.respond_to?("#{k}=") }
end
def object
return unless self.class.klass
if self.send(find_by).present?
@object ||= self.class.klass.where(find_by => self.send(find_by)).first
else
@object ||= self.class.klass.new
end
end
def object=(obj)
@object = obj
self.id = obj.id if obj.id.present?
end
def settable_field?(field_name)
self.respond_to?("#{field_name}=") && object.respond_to?("#{field_name}=")
end
end
end
| ruby | MIT | b9a6822024f63f7b48b5fcdb601b4f06f17abbb3 | 2026-01-04T17:54:46.250539Z | false |
trunkclub/faceted | https://github.com/trunkclub/faceted/blob/b9a6822024f63f7b48b5fcdb601b4f06f17abbb3/lib/faceted/controller.rb | lib/faceted/controller.rb | module Faceted
module Controller
# For rendering a response with a single object, e.g.
# render_response(@address)
def render_response(obj, code=nil)
render :json => {
success: obj.success,
response: obj.to_hash,
errors: obj.errors
}, :status => code || obj.success ? 200 : 400
end
# For rendering a response with a multiple objects, e.g.
# render_response_with_collection(:addresses, @addresses)
def render_response_with_collection(key, array)
render :json => {
success: true,
response: {"#{key}".to_sym => array},
errors: nil
}
end
# In your base API controller:
# rescue_from ActiveRecord::RecordNotFound, :with => :record_not_found
def render_400(exception)
render :json => {
success: false,
response: nil,
errors: "#{exception.message}"
}, :status => 400
end
# In your base API controller:
# rescue_from Exception, :with => :render_500
def render_500(exception)
Rails.logger.info("!!! #{self.class.name} exception caught: #{exception} #{exception.backtrace.join("\n")}")
render :json => {
success: false,
response: nil,
errors: "#{exception.message}"
}, :status => 500
end
end
end | ruby | MIT | b9a6822024f63f7b48b5fcdb601b4f06f17abbb3 | 2026-01-04T17:54:46.250539Z | false |
trunkclub/faceted | https://github.com/trunkclub/faceted/blob/b9a6822024f63f7b48b5fcdb601b4f06f17abbb3/lib/faceted/model.rb | lib/faceted/model.rb | module Faceted
module Model
require 'json'
require 'active_support/core_ext/hash'
# Class methods ============================================================
module ModelClassMethods
def build_association_from(field)
bare_name = field.gsub(/_id$/, '')
if field =~ /_id$/
klass = eval "#{scope}#{bare_name.classify}"
fields << bare_name.to_sym
define_method :"#{bare_name}" do
klass.new(:id => self.send(field))
end
end
end
def create(params={})
obj = self.new(params)
obj.save
obj
end
def field(name, args={})
fields << name
define_method :"#{name}" do
val = instance_variable_get("@#{name}")
val.nil? ? args[:default] : val
end
unless args[:read_only]
define_method :"#{name}=" do |val|
instance_variable_set("@#{name}", val)
end
end
build_association_from(name.to_s) if name.to_s.include?("id") && ! args[:skip_association]
end
def fields
@fields ||= [:id, :excludes]
end
def from(object, args={})
materialize([object], args).first
end
def materialize(objects=[], args={})
objects.compact.inject([]) do |a, object|
interface = self.new(args)
interface.send(:object=, object)
interface.send(:initialize_with_object)
a << interface
end
end
def scope
parent.to_s == "Object" ? "::" : "#{parent.to_s}::"
end
end
end
end
| ruby | MIT | b9a6822024f63f7b48b5fcdb601b4f06f17abbb3 | 2026-01-04T17:54:46.250539Z | false |
anjlab/rails-data-migrations | https://github.com/anjlab/rails-data-migrations/blob/727f933eec032a8f8e53364c5134d16d4bef1d75/spec/data_migrations_spec.rb | spec/data_migrations_spec.rb | # frozen_string_literal: true
require 'spec_helper'
describe RailsDataMigrations do
it 'checks for migration log table existence' do
expect(RailsDataMigrations::Migrator.migrations_table_exists?(ActiveRecord::Base.connection)).to be_truthy
expect(RailsDataMigrations::Migrator.get_all_versions).to be_blank
end
it 'has no migrations at the start' do
expect(RailsDataMigrations::Migrator.current_version).to eq(0)
expect(RailsDataMigrations::LogEntry.count).to eq(0)
end
context 'generator' do
let(:migration_name) { 'test_migration' }
let(:file_name) { 'spec/db/data-migrations/20161031000000_test_migration.rb' }
before(:each) do
allow(Time).to receive(:now).and_return(Time.utc(2016, 10, 31))
Rails::Generators.invoke('data_migration', [migration_name])
end
it 'creates non-empty migration file' do
expect(File.exist?(file_name)).to be_truthy
expect(File.size(file_name)).to be > 0
end
it 'creates valid migration class' do
# rubocop:disable Security/Eval
eval(File.open(file_name).read)
# rubocop:enable Security/Eval
klass = migration_name.classify.constantize
expect(klass.superclass).to eq(ActiveRecord::DataMigration)
expect(klass.instance_methods(false)).to eq([:up])
end
end
context 'migrator' do
before(:each) do
allow(Time).to receive(:now).and_return(Time.utc(2016, 11, 1, 2, 3, 4))
Rails::Generators.invoke('data_migration', ['test'])
end
def load_rake_rasks
load File.expand_path('../lib/tasks/data_migrations.rake', __dir__)
Rake::Task.define_task(:environment)
end
it 'lists pending migrations' do
load_rake_rasks
expect { Rake::Task['data:migrate:pending'].execute }.not_to raise_error
end
it 'list migration file' do
expect(RailsDataMigrations::Migrator.list_migrations.size).to eq(1)
end
it 'applies pending migrations only once' do
expect(RailsDataMigrations::LogEntry.count).to eq(0)
load_rake_rasks
2.times do
Rake::Task['data:migrate'].execute
expect(RailsDataMigrations::Migrator.current_version).to eq(20161101020304)
expect(RailsDataMigrations::LogEntry.count).to eq(1)
end
end
it 'requires VERSION to run a single migration' do
ENV['VERSION'] = nil
load_rake_rasks
expect { Rake::Task['data:migrate:up'].execute }.to raise_error(RuntimeError, 'VERSION is required')
expect { Rake::Task['data:migrate:down'].execute }.to raise_error(RuntimeError, 'VERSION is required')
end
it 'marks pending migrations complete without running them' do
load_rake_rasks
allow(RailsDataMigrations::Migrator).to receive(:run) { true }
Rake::Task['data:reset'].execute
expect(RailsDataMigrations::LogEntry.count).to eq(1)
expect(RailsDataMigrations::Migrator).not_to have_received(:run)
end
end
end
| ruby | MIT | 727f933eec032a8f8e53364c5134d16d4bef1d75 | 2026-01-04T17:54:52.718645Z | false |
anjlab/rails-data-migrations | https://github.com/anjlab/rails-data-migrations/blob/727f933eec032a8f8e53364c5134d16d4bef1d75/spec/spec_helper.rb | spec/spec_helper.rb | # frozen_string_literal: true
require 'rails/generators'
require 'rake'
$LOAD_PATH.unshift File.expand_path('../lib', __dir__)
require 'rails-data-migrations'
ActiveRecord::Base.establish_connection adapter: 'sqlite3', database: ':memory:'
RSpec.configure do |config|
config.raise_errors_for_deprecations!
config.before(:all) do
RailsDataMigrations::LogEntry.create_table
end
config.before(:each) do
RailsDataMigrations::LogEntry.delete_all
# stub migrations folder
allow(RailsDataMigrations::Migrator).to receive(:migrations_path).and_return('spec/db/data-migrations')
# remove migration files
`rm -rf spec/db/data-migrations`
ENV['VERSION'] = nil
end
end
| ruby | MIT | 727f933eec032a8f8e53364c5134d16d4bef1d75 | 2026-01-04T17:54:52.718645Z | false |
anjlab/rails-data-migrations | https://github.com/anjlab/rails-data-migrations/blob/727f933eec032a8f8e53364c5134d16d4bef1d75/lib/rails-data-migrations.rb | lib/rails-data-migrations.rb | # frozen_string_literal: true
require 'rails'
require 'active_record'
require 'active_record/data_migration'
require 'rails_data_migrations/version'
require 'rails_data_migrations/log_entry'
require 'rails_data_migrations/migrator'
require 'rails_data_migrations/railtie'
| ruby | MIT | 727f933eec032a8f8e53364c5134d16d4bef1d75 | 2026-01-04T17:54:52.718645Z | false |
anjlab/rails-data-migrations | https://github.com/anjlab/rails-data-migrations/blob/727f933eec032a8f8e53364c5134d16d4bef1d75/lib/rails_data_migrations/version.rb | lib/rails_data_migrations/version.rb | # frozen_string_literal: true
module RailsDataMigrations
VERSION = '1.3.0'
end
| ruby | MIT | 727f933eec032a8f8e53364c5134d16d4bef1d75 | 2026-01-04T17:54:52.718645Z | false |
anjlab/rails-data-migrations | https://github.com/anjlab/rails-data-migrations/blob/727f933eec032a8f8e53364c5134d16d4bef1d75/lib/rails_data_migrations/railtie.rb | lib/rails_data_migrations/railtie.rb | # frozen_string_literal: true
require 'rails'
module RailsDataMigrations
class Railtie < ::Rails::Railtie
rake_tasks do
load File.join(File.dirname(__FILE__), '..', 'tasks/data_migrations.rake')
end
end
end | ruby | MIT | 727f933eec032a8f8e53364c5134d16d4bef1d75 | 2026-01-04T17:54:52.718645Z | false |
anjlab/rails-data-migrations | https://github.com/anjlab/rails-data-migrations/blob/727f933eec032a8f8e53364c5134d16d4bef1d75/lib/rails_data_migrations/log_entry.rb | lib/rails_data_migrations/log_entry.rb | # frozen_string_literal: true
module RailsDataMigrations
module SharedMethods
def table_name
"#{ActiveRecord::Base.table_name_prefix}data_migrations#{ActiveRecord::Base.table_name_suffix}"
end
def index_name
"#{table_name_prefix}unique_data_migrations#{table_name_suffix}"
end
end
if Gem::Version.new('7.1.0') >= Gem::Version.new(::ActiveRecord.version)
class LogEntry < ::ActiveRecord::SchemaMigration
class << self
include SharedMethods
end
end
else
class LogEntry < ::ActiveRecord::Base
class << self
include SharedMethods
def create_table
::ActiveRecord::SchemaMigration.define_method(:table_name) do
"#{::ActiveRecord::Base.table_name_prefix}data_migrations#{::ActiveRecord::Base.table_name_suffix}"
end
::ActiveRecord::Base.connection.schema_migration.create_table
end
end
end
end
end | ruby | MIT | 727f933eec032a8f8e53364c5134d16d4bef1d75 | 2026-01-04T17:54:52.718645Z | false |
anjlab/rails-data-migrations | https://github.com/anjlab/rails-data-migrations/blob/727f933eec032a8f8e53364c5134d16d4bef1d75/lib/rails_data_migrations/migrator.rb | lib/rails_data_migrations/migrator.rb | # frozen_string_literal: true
module RailsDataMigrations
class Migrator < ::ActiveRecord::Migrator
MIGRATOR_SALT = 2053462855
def record_version_state_after_migrating(version)
if down?
migrated.delete(version)
LogEntry.where(version: version.to_s).delete_all
else
migrated << version
LogEntry.create!(version: version.to_s)
end
end
class << self
def migrations_table_exists?(connection = ActiveRecord::Base.connection)
table_check_method = connection.respond_to?(:data_source_exists?) ? :data_source_exists? : :table_exists?
connection.send(table_check_method, schema_migrations_table_name)
end
def get_all_versions(connection = ActiveRecord::Base.connection)
if migrations_table_exists?(connection)
LogEntry.all.map { |x| x.version.to_i }.sort
else
[]
end
end
def current_version
get_all_versions.max || 0
end
def schema_migrations_table_name
LogEntry.table_name
end
def migrations_path
'db/data_migrations'
end
def rails_6_0?
Rails::VERSION::MAJOR >= 6
end
def rails_5_2?
Rails::VERSION::MAJOR > 5 || (Rails::VERSION::MAJOR == 5 && Rails::VERSION::MINOR >= 2)
end
def rails_7_1?
Rails::VERSION::MAJOR == 7 && Rails::VERSION::MINOR >= 1
end
def list_migrations
if rails_7_1?
::ActiveRecord::MigrationContext.new(
migrations_path, ::ActiveRecord::Base.connection.schema_migration
).migrations
elsif rails_6_0?
::ActiveRecord::MigrationContext.new(migrations_path, ::ActiveRecord::SchemaMigration).migrations
elsif rails_5_2?
::ActiveRecord::MigrationContext.new(migrations_path).migrations
else
migrations(migrations_path)
end
end
def list_pending_migrations
if rails_5_2?
already_migrated = get_all_versions
list_migrations.reject { |m| already_migrated.include?(m.version) }
else
open(migrations_path).pending_migrations # rubocop:disable Security/Open
end
end
def run_migration(direction, migrations_path, version)
if rails_7_1?
new(
direction,
list_migrations,
::ActiveRecord::Base.connection.schema_migration,
::ActiveRecord::InternalMetadata.new(ActiveRecord::Base.connection),
version
).run
elsif rails_6_0?
new(direction, list_migrations, ::ActiveRecord::SchemaMigration, version).run
elsif rails_5_2?
new(direction, list_migrations, version).run
else
run(direction, migrations_path, version)
end
end
end
end
end
| ruby | MIT | 727f933eec032a8f8e53364c5134d16d4bef1d75 | 2026-01-04T17:54:52.718645Z | false |
anjlab/rails-data-migrations | https://github.com/anjlab/rails-data-migrations/blob/727f933eec032a8f8e53364c5134d16d4bef1d75/lib/generators/data_migration_generator.rb | lib/generators/data_migration_generator.rb | # frozen_string_literal: true
require 'rails/generators'
require 'rails-data-migrations'
class DataMigrationGenerator < Rails::Generators::NamedBase
source_root File.expand_path('templates', __dir__)
def create_migration_file
migration_file_name =
"#{RailsDataMigrations::Migrator.migrations_path}/#{Time.now.utc.strftime('%Y%m%d%H%M%S')}_#{file_name}.rb"
copy_file 'data_migration_generator.rb', migration_file_name do |content|
content.sub(/ClassName/, file_name.camelize)
end
end
end
| ruby | MIT | 727f933eec032a8f8e53364c5134d16d4bef1d75 | 2026-01-04T17:54:52.718645Z | false |
anjlab/rails-data-migrations | https://github.com/anjlab/rails-data-migrations/blob/727f933eec032a8f8e53364c5134d16d4bef1d75/lib/generators/templates/data_migration_generator.rb | lib/generators/templates/data_migration_generator.rb | # frozen_string_literal: true
class ClassName < ActiveRecord::DataMigration
def up
# put your code here
end
end | ruby | MIT | 727f933eec032a8f8e53364c5134d16d4bef1d75 | 2026-01-04T17:54:52.718645Z | false |
anjlab/rails-data-migrations | https://github.com/anjlab/rails-data-migrations/blob/727f933eec032a8f8e53364c5134d16d4bef1d75/lib/active_record/data_migration.rb | lib/active_record/data_migration.rb | # frozen_string_literal: true
require 'rails/version'
module ActiveRecord
class DataMigration < (Rails::VERSION::MAJOR >= 5 ? Migration[5.0] : Migration)
# base class (extend with any useful helpers)
def down
raise IrreversibleMigration
end
end
end | ruby | MIT | 727f933eec032a8f8e53364c5134d16d4bef1d75 | 2026-01-04T17:54:52.718645Z | false |
PeriscopeData/redshift-udfs | https://github.com/PeriscopeData/redshift-udfs/blob/d9cd02c9bbd5aec39a24996ac2548f96ffa5c381/udf.rb | udf.rb | require_relative 'udf_harness'
class Runner
ARGS_HELP = """
Usage:
ruby #{__FILE__} <action> [udf_name]
Actions:
load Loads UDFs into your database
drop Removes UDFs from your database
test Runs UDF unit tests on your database
print Pretty-print SQL for making the UDFs
Examples:
ruby #{__FILE__} load
ruby #{__FILE__} drop harmonic_mean
ruby #{__FILE__} test json_array_first
ruby #{__FILE__} print
"""
def self.run(args = [])
if args.nil? or args.empty?
puts ARGS_HELP
exit
end
u = UdfHarness.new(args[1])
case args.first.to_sym
when :load then u.create_udfs
when :drop then u.drop_udfs
when :test then u.test_udfs
when :print then u.print_udfs
else
puts "Args not understood, showing help instead."
puts ARGS_HELP
exit
end
end
end
Runner.run(ARGV) if __FILE__ == $PROGRAM_NAME
| ruby | MIT | d9cd02c9bbd5aec39a24996ac2548f96ffa5c381 | 2026-01-04T17:54:54.457515Z | false |
PeriscopeData/redshift-udfs | https://github.com/PeriscopeData/redshift-udfs/blob/d9cd02c9bbd5aec39a24996ac2548f96ffa5c381/udf_harness.rb | udf_harness.rb | require 'pg'
require 'yaml'
Dir[File.join(File.dirname(__FILE__), 'lib', '*.rb')].each do |file|
require_relative File.join('lib', File.basename(file))
end
class UdfHarness
def initialize(only_udf = nil)
@udfs = [
UdfJsonArrays::UDFS,
UdfMysqlCompat::UDFS,
UdfTimeHelpers::UDFS,
UdfStringUtils::UDFS,
UdfNumberUtils::UDFS,
UdfStats::UDFS,
].flatten.select { |u| only_udf.nil? or u[:name] == only_udf.to_sym }
end
def create_udfs
@udfs.each { |udf| create_udf(udf) }
end
def drop_udfs
@udfs.each { |udf| drop_udf(udf) }
end
def test_udfs
create_udfs
@udfs.each { |udf| test_udf(udf) }
end
def print_udfs
@udfs.each { |udf| puts make_create_query(udf) }
end
private
# --------------------------- Running Queries --------------------
def get_env_or_panic!(var)
val = YAML.load(File.open(File.join(File.dirname(__FILE__), 'config.yaml')))[var]
val ||= ENV[var].to_s.strip
if val == ''
puts "Error: Missing value for #{var}"
exit
end
val
end
def connect!
@conn ||= PG.connect({
host: get_env_or_panic!('UDF_CLUSTER_HOST'),
port: get_env_or_panic!('UDF_CLUSTER_PORT'),
dbname: get_env_or_panic!('UDF_CLUSTER_DB_NAME'),
user: get_env_or_panic!('UDF_CLUSTER_USER'),
password: get_env_or_panic!('UDF_CLUSTER_PASSWORD'),
})
end
def query(str, print_errors = false)
result = {rows: nil, error: nil}
begin
connect!.exec(str) do |r|
result[:rows] = r.values
end
rescue => ex
puts ex.message if print_errors
result[:error] = ex.message
end
result
end
# --------------------------- Query Generation ------------------------------
def make_drop_query(udf)
"drop #{udf[:type]} #{udf[:name]}(#{udf[:params]}) cascade"
end
def make_create_query(udf)
if udf[:type] == :function
make_header(udf) + make_function_create_query(udf)
elsif udf[:type] == :aggregate
make_header(udf) + make_aggregate_query(udf)
end
end
def make_header(udf)
examples = make_examples(udf)
desc = udf[:description]
desc = "Aggregate helper: #{desc}" if udf[:name].to_s.start_with?('agg_')
%~
/*
#{udf[:name].to_s.upcase}
#{desc}
Examples:
#{examples.map { |e| ' ' + e.sub('?', udf[:name].to_s) }.join("\n#{' ' * 6}")}
*/~
end
def make_function_create_query(udf)
%~
create or replace function #{udf[:name]} (#{udf[:params]})
returns #{udf[:return_type]}
stable as $$
#{udf[:body].split("\n").map { |r| r.sub(/^\s{2}/, '') }.join("\n").strip}
$$ language plpythonu;
~
end
def make_aggregate_query(aggregate_udf)
%~
create aggregate #{aggregate_udf[:name]} (#{aggregate_udf[:params]})
(
initfunc = #{aggregate_udf[:init_function]},
aggfunc = #{aggregate_udf[:agg_function]},
finalizefunc = #{aggregate_udf[:finalize_function]}
);
~
end
def make_examples(udf)
examples = []
udf[:tests].each do |test|
next unless test[:example]
expect = test[:expect]
expect = "'#{expect}'" if expect.class == String
if test[:query].present?
examples << "#{test[:query]} --> #{expect}"
elsif test[:rows].present?
examples << "[#{test[:rows].join(", ")}] --> #{expect}"
end
end
examples
end
# --------------------------------- Creating UDFs ----------------------------
def create_udf(udf)
puts "Making #{udf[:type]} #{udf[:name]}"
drop_udf(udf, true)
result = query(make_create_query(udf))
puts "Error: #{result[:error]}" if result[:error].present?
end
def drop_udf(udf, silent = false)
puts "Dropping #{udf[:type]} #{udf[:name]}" unless silent
query(make_drop_query(udf))
end
# --------------------------------- Testing UDFs ----------------------------
def test_udf(udf)
print "Testing #{udf[:type]} #{udf[:name]}"
test_function(udf)
print "\n"
end
def test_function(udf)
udf[:tests].each do |test|
print compare_test_results(test[:query].sub("?", udf[:name].to_s), test)
end
end
def test_aggregate(aggregate_udf)
aggregate_udf[:tests].each do |test|
union_rows = test[:rows].map do |r|
casted_row = r
casted_row = "'#{r}'::varchar" if r.class == String
casted_row = "'#{r}'::float" if r.class == Float
"select #{casted_row} as _test_c\n"
end
query = %~
with _test_t as (#{union_rows.join(' union all ')})
select #{aggregate_udf[:name]}(_test_c) from _test_t
~
print compare_test_results(query, test)
end
end
def compare_test_results(q, test)
result = query(q)
if result[:error].present?
return "\nError on #{test}: #{result[:error]}\n"
elsif !test[:skip]
result_val = result[:rows][0][0]
result_val = result_val.to_i if test[:expect].class == Fixnum
result_val = result_val.to_f if test[:expect].class == Float
if result_val != test[:expect]
return "\nMismatch on #{test}: #{result_val || 'null'} != #{test[:expect] || 'null'}\n"
end
end
"."
end
end
| ruby | MIT | d9cd02c9bbd5aec39a24996ac2548f96ffa5c381 | 2026-01-04T17:54:54.457515Z | false |
PeriscopeData/redshift-udfs | https://github.com/PeriscopeData/redshift-udfs/blob/d9cd02c9bbd5aec39a24996ac2548f96ffa5c381/lib/udf_string_utils.rb | lib/udf_string_utils.rb | class UdfStringUtils
UDFS = [
{
type: :function,
name: :email_name,
description: "Gets the part of the email address before the @ sign",
params: "email varchar(max)",
return_type: "varchar(max)",
body: %~
if not email:
return None
return email.split('@')[0]
~,
tests: [
{query: "select ?('sam@company.com')", expect: 'sam', example: true},
{query: "select ?('alex@othercompany.com')", expect: 'alex', example: true},
{query: "select ?('bonk')", expect: 'bonk'},
{query: "select ?(null)", expect: nil},
]
}, {
type: :function,
name: :email_domain,
description: "Gets the part of the email address after the @ sign",
params: "email varchar(max)",
return_type: "varchar(max)",
body: %~
if not email:
return None
return email.split('@')[-1]
~,
tests: [
{query: "select ?('sam@company.com')", expect: 'company.com', example: true},
{query: "select ?('alex@othercompany.com')", expect: 'othercompany.com', example: true},
{query: "select ?('bonk')", expect: 'bonk'},
{query: "select ?(null)", expect: nil},
]
}, {
type: :function,
name: :url_protocol,
description: "Gets the protocol of the URL",
params: "url varchar(max)",
return_type: "varchar(max)",
body: %~
from urlparse import urlparse
if not url:
return None
try:
u = urlparse(url)
return u.scheme
except ValueError:
return None
~,
tests: [
{query: "select ?('http://www.google.com/a')", expect: 'http', example: true},
{query: "select ?('https://gmail.com/b')", expect: 'https', example: true},
{query: "select ?('sftp://company.com/c')", expect: 'sftp', example: true},
{query: "select ?('bonk')", expect: ''},
{query: "select ?(null)", expect: nil},
]
}, {
type: :function,
name: :url_domain,
description: "Gets the domain (and subdomain if present) of the URL",
params: "url varchar(max)",
return_type: "varchar(max)",
body: %~
from urlparse import urlparse
if not url:
return None
try:
u = urlparse(url)
return u.netloc
except ValueError:
return None
~,
tests: [
{query: "select ?('http://www.google.com/a')", expect: 'www.google.com', example: true},
{query: "select ?('https://gmail.com/b')", expect: 'gmail.com', example: true},
{query: "select ?('bonk')", expect: ''},
{query: "select ?(null)", expect: nil},
]
}, {
type: :function,
name: :url_path,
description: "Gets the domain (and subdomain if present) of the URL",
params: "url varchar(max)",
return_type: "varchar(max)",
body: %~
from urlparse import urlparse
if not url:
return None
try:
u = urlparse(url)
return u.path
except ValueError:
return None
~,
tests: [
{query: "select ?('http://www.google.com/search/images?query=bob')", expect: '/search/images', example: true},
{query: "select ?('https://gmail.com/mail.php?user=bob')", expect: '/mail.php', example: true},
{query: "select ?('bonk')", expect: 'bonk'},
{query: "select ?(null)", expect: nil},
]
}, {
type: :function,
name: :url_param,
description: "Extract a parameter from a URL",
params: "url varchar(max), param varchar(max)",
return_type: "varchar(max)",
body: %~
import urlparse
if not url:
return None
try:
u = urlparse.urlparse(url)
return urlparse.parse_qs(u.query)[param][0]
except KeyError:
return None
~,
tests: [
{query: "select ?('http://www.google.com/search/images?query=bob', 'query')", expect: 'bob', example: true},
{query: "select ?('https://gmail.com/mail.php?user=bob&account=work', 'user')", expect: 'bob', example: true},
{query: "select ?('bonk', 'bonk')", expect: nil},
{query: "select ?(null, null)", expect: nil},
]
}, {
type: :function,
name: :split_count,
description: "Split a string on another string and count the members",
params: "str varchar(max), delim varchar(max)",
return_type: "int",
body: %~
if not str or not delim:
return None
return len(str.split(delim))
~,
tests: [
{query: "select ?('foo,bar,baz', ',')", expect: 3, example: true},
{query: "select ?('foo', 'bar')", expect: 1, example: true},
{query: "select ?('foo,bar', 'o,b')", expect: 2},
]
},
{
type: :function,
name: :titlecase,
description: "Format a string as titlecase",
params: "str varchar(max)",
return_type: "varchar(max)",
body: %~
if not str:
return None
return str.title()
~,
tests: [
{query: "select ?('this is a title')", expect: 'This Is A Title', example: true},
{query: "select ?('Already A Title')", expect: 'Already A Title', example: true},
{query: "select ?('')", expect: nil},
{query: "select ?(null)", expect: nil},
]
}, {
type: :function,
name: :str_multiply,
description: "Repeat a string N times",
params: "str varchar(max), times integer",
return_type: "varchar(max)",
body: %~
if not str:
return None
return str * times
~,
tests: [
{query: "select ?('*', 10)", expect: '**********', example: true},
{query: "select ?('abc ', 3)", expect: 'abc abc abc ', example: true},
{query: "select ?('abc ', -3)", expect: ''},
{query: "select ?('', 0)", expect: nil},
{query: "select ?(null, 10)", expect: nil},
]
}, {
type: :function,
name: :str_index,
description: "Find the index of the first occurrence of a substring, or -1 if not found",
params: "full_str varchar(max), find_substr varchar(max)",
return_type: "integer",
body: %~
if not full_str or not find_substr:
return None
return full_str.find(find_substr)
~,
tests: [
{query: "select ?('Apples Oranges Pears', 'Oranges')", expect: 7, example: true},
{query: "select ?('Apples Oranges Pears', 'Bananas')", expect: -1, example: true},
{query: "select ?('abc', 'd')", expect: -1},
{query: "select ?('', '')", expect: nil},
{query: "select ?(null, null)", expect: nil},
]
}, {
type: :function,
name: :str_rindex,
description: "Find the index of the last occurrence of a substring, or -1 if not found",
params: "full_str varchar(max), find_substr varchar(max)",
return_type: "integer",
body: %~
if not full_str or not find_substr:
return None
return full_str.rfind(find_substr)
~,
tests: [
{query: "select ?('A B C A B C', 'C')", expect: 10, example: true},
{query: "select ?('Apples Oranges Pears Oranges', 'Oranges')", expect: 21, example: true},
{query: "select ?('Apples Oranges', 'Bananas')", expect: -1, example: true},
{query: "select ?('abc', 'd')", expect: -1},
{query: "select ?('', '')", expect: nil},
{query: "select ?(null, null)", expect: nil},
]
}, {
type: :function,
name: :str_count,
description: "Counts the number of occurrences of a substring within a string",
params: "full_str varchar(max), find_substr varchar(max)",
return_type: "integer",
body: %~
if not full_str or not find_substr:
return None
return full_str.count(find_substr)
~,
tests: [
{query: "select ?('abbbc', 'b')", expect: 3, example: true},
{query: "select ?('Apples Bananas', 'an')", expect: 2, example: true},
{query: "select ?('aaa', 'A')", expect: 0, example: true},
{query: "select ?('abc', 'd')", expect: 0},
{query: "select ?('', '')", expect: nil},
{query: "select ?(null, null)", expect: nil},
]
}, {
type: :function,
name: :remove_accents,
description: "Remove accents from a string",
params: "str varchar(max)",
return_type: "varchar(max)",
body: %~
import unicodedata
if not str:
return None
str = str.decode('utf-8')
return unicodedata.normalize('NFKD', str).encode('ASCII', 'ignore')
~,
tests: [
{query: "select ?('café')", expect: 'cafe', example: true},
{query: "select ?('')", expect: nil},
{query: "select ?(null)", expect: nil},
]
}
]
end
| ruby | MIT | d9cd02c9bbd5aec39a24996ac2548f96ffa5c381 | 2026-01-04T17:54:54.457515Z | false |
PeriscopeData/redshift-udfs | https://github.com/PeriscopeData/redshift-udfs/blob/d9cd02c9bbd5aec39a24996ac2548f96ffa5c381/lib/udf_time_helpers.rb | lib/udf_time_helpers.rb | class UdfTimeHelpers
UDFS = [
{
type: :function,
name: :now,
description: "Returns the current time as a timestamp in UTC",
params: nil,
return_type: "timestamp",
body: %~
from datetime import datetime
datetime.utcnow()
~,
tests: [
{query: "select ?()", expect: '2015-03-30 21:32:15.553489+00', example: true, skip: true},
]
}, {
type: :function,
name: :posix_timestamp,
description: "Returns the number of seconds from 1970-01-01 for this timestamp",
params: "ts timestamp",
return_type: "real",
body: %~
from datetime import datetime
if not ts:
return None
return (ts - datetime(1970, 1, 1)).total_seconds()
~,
tests: [
{query: "select ?('2015-03-30 21:32:15'::timestamp)", expect: '1427751521.107629', example: true, skip: true},
]
},
]
end
| ruby | MIT | d9cd02c9bbd5aec39a24996ac2548f96ffa5c381 | 2026-01-04T17:54:54.457515Z | false |
PeriscopeData/redshift-udfs | https://github.com/PeriscopeData/redshift-udfs/blob/d9cd02c9bbd5aec39a24996ac2548f96ffa5c381/lib/udf_json_arrays.rb | lib/udf_json_arrays.rb | class UdfJsonArrays
UDFS = [
{
type: :function,
name: :json_array_first,
description: "Returns the first element of a JSON array as a string",
params: "j varchar(max)",
return_type: "varchar(max)",
body: %~
import json
if not j:
return None
try:
arr = json.loads(j)
except ValueError:
return None
if len(arr) == 0:
return None
return str(arr[0])
~,
tests: [
{query: "select ?('[\"a\", \"b\"]')", expect: "a", example: true},
{query: "select ?('[1, 2, 3]')", expect: "1", example: true},
{query: "select ?('[4]')", expect: "4"},
{query: "select ?('[]')", expect: nil},
{query: "select ?('')", expect: nil},
{query: "select ?(null)", expect: nil},
{query: "select ?('abc')", expect: nil},
]
}, {
type: :function,
name: :json_array_last,
description: "Returns the last element of a JSON array as a string",
params: "j varchar(max)",
return_type: "varchar(max)",
body: %~
import json
if not j:
return None
try:
arr = json.loads(j)
except ValueError:
return None
if len(arr) == 0:
return None
return str(arr[-1])
~,
tests: [
{query: "select ?('[\"a\", \"b\"]')", expect: "b", example: true},
{query: "select ?('[1, 2, 3]')", expect: "3", example: true},
{query: "select ?('[4]')", expect: "4"},
{query: "select ?('[]')", expect: nil},
{query: "select ?('')", expect: nil},
{query: "select ?(null)", expect: nil},
{query: "select ?('abc')", expect: nil},
]
}, {
type: :function,
name: :json_array_nth,
description: "Returns the Nth 0-indexed element of a JSON array as a string",
params: "j varchar(max), i integer",
return_type: "varchar(max)",
body: %~
import json
if not j or (not i and i != 0) or i < 0:
return None
try:
arr = json.loads(j)
except ValueError:
return None
if len(arr) <= i:
return None
return str(arr[i])
~,
tests: [
{query: "select ?('[\"a\", \"b\"]', 0)", expect: "a", example: true},
{query: "select ?('[\"a\", \"b\"]', 1)", expect: "b"},
{query: "select ?('[\"a\", \"b\"]', -1)", expect: nil},
{query: "select ?('[1,2,3]', 3)", expect: nil},
{query: "select ?('[1, 2, 3]', 1)", expect: "2", example: true},
{query: "select ?('[4]', null)", expect: nil},
{query: "select ?('[]', 4)", expect: nil},
{query: "select ?('', 3)", expect: nil},
{query: "select ?(null, null)", expect: nil},
{query: "select ?('abc', 1)", expect: nil},
]
}, {
type: :function,
name: :json_array_sort,
description: "Returns sorts a JSON array and returns it as a string, second param sets direction",
params: "j varchar(max), ascending boolean",
return_type: "varchar(max)",
body: %~
import json
if not j:
return None
try:
arr = json.loads(j)
except ValueError:
return None
if not ascending:
arr = sorted(arr, reverse=True)
else:
arr = sorted(arr)
return json.dumps(arr)
~,
tests: [
{query: "select ?('[\"a\",\"c\",\"b\"]', true)", expect: '["a", "b", "c"]', example: true},
{query: "select ?('[\"a\",\"c\",\"b\"]', false)", expect: '["c", "b", "a"]'},
{query: "select ?('[1, 3, 2]', true)", expect: '[1, 2, 3]', example: true},
{query: "select ?('[4]', null)", expect: "[4]"},
{query: "select ?('[]', true)", expect: "[]"},
{query: "select ?('', true)", expect: nil},
{query: "select ?(null, null)", expect: nil},
{query: "select ?('abc', 1)", expect: nil},
]
}, {
type: :function,
name: :json_array_reverse,
description: "Reverses a JSON array and returns it as a string",
params: "j varchar(max)",
return_type: "varchar(max)",
body: %~
import json
if not j:
return None
try:
arr = json.loads(j)
except ValueError:
return None
return json.dumps(arr[::-1])
~,
tests: [
{query: "select ?('[\"a\",\"c\",\"b\"]')", expect: '["b", "c", "a"]', example: true},
{query: "select ?('[1, 3, 2]')", expect: '[2, 3, 1]', example: true},
{query: "select ?('[4]')", expect: "[4]"},
{query: "select ?('[]')", expect: "[]"},
{query: "select ?('')", expect: nil},
{query: "select ?(null)", expect: nil},
{query: "select ?('abc')", expect: nil},
]
}, {
type: :function,
name: :json_array_pop,
description: "Removes the last element from a JSON array and returns the remaining array as a string",
params: "j varchar(max)",
return_type: "varchar(max)",
body: %~
import json
if not j:
return None
try:
arr = json.loads(j)
except ValueError:
return None
if len(arr) > 0:
arr.pop()
return json.dumps(arr)
~,
tests: [
{query: "select ?('[\"a\",\"c\",\"b\"]')", expect: '["a", "c"]', example: true},
{query: "select ?('[1, 3, 2]')", expect: '[1, 3]', example: true},
{query: "select ?('[4]')", expect: "[]"},
{query: "select ?('[]')", expect: "[]"},
{query: "select ?('')", expect: nil},
{query: "select ?(null)", expect: nil},
{query: "select ?('abc')", expect: nil},
]
}, {
type: :function,
name: :json_array_push,
description: "Adds a new element to a JSON array and returns the new array as a string",
params: "j varchar(max), value varchar(max)",
return_type: "varchar(max)",
body: %~
import json
if not j:
arr = []
else:
try:
arr = json.loads(j)
except ValueError:
arr = []
arr.append(value)
return json.dumps(arr)
~,
tests: [
{query: "select ?('[\"a\",\"c\",\"b\"]', 'd')", expect: '["a", "c", "b", "d"]', example: true},
{query: "select ?('[1, 3, 2]', '4')", expect: '[1, 3, 2, "4"]', example: true},
{query: "select ?('[4]', 'a')", expect: '[4, "a"]'},
{query: "select ?('[]', '3')", expect: '["3"]'},
{query: "select ?('', '5')", expect: '["5"]'},
{query: "select ?(null, null)", expect: "[null]"},
{query: "select ?('abc', 'a')", expect: '["a"]'},
]
}, {
type: :function,
name: :json_array_concat,
description: "Concatenates two JSON arrays and returns the new array as a string",
params: "j varchar(max), k varchar(max)",
return_type: "varchar(max)",
body: %~
import json
if not j:
return k
if not k:
return j
try:
arr_j = json.loads(j)
arr_k = json.loads(k)
except ValueError:
return None
arr_j.extend(arr_k)
return json.dumps(arr_j)
~,
tests: [
{query: "select ?('[\"a\",\"c\",\"b\"]', '[\"d\",\"e\"]')", expect: '["a", "c", "b", "d", "e"]', example: true},
{query: "select ?('[1, 3, 2]', '[4]')", expect: '[1, 3, 2, 4]', example: true},
{query: "select ?('[4]', '[\"a\"]')", expect: '[4, "a"]'},
{query: "select ?('[]', '[3]')", expect: '[3]'},
{query: "select ?('', '5')", expect: '5'},
{query: "select ?('4', null)", expect: "4"},
{query: "select ?('abc', 'a')", expect: nil},
]
}
]
end
| ruby | MIT | d9cd02c9bbd5aec39a24996ac2548f96ffa5c381 | 2026-01-04T17:54:54.457515Z | false |
PeriscopeData/redshift-udfs | https://github.com/PeriscopeData/redshift-udfs/blob/d9cd02c9bbd5aec39a24996ac2548f96ffa5c381/lib/udf_mysql_compat.rb | lib/udf_mysql_compat.rb | class UdfMysqlCompat
UDFS = [
{
type: :function,
name: :mysql_year,
description: "Extract the year from a datetime",
params: "ts timestamp",
return_type: "integer",
body: %~
if not ts:
return None
return ts.year
~,
tests: [
{query: "select ?('2015-01-03T04:05:06.07'::timestamp)", expect: 2015, example: true},
{query: "select ?('2016-02-04T04:05:06.07 -07'::timestamp)", expect: 2016, example: true},
{query: "select ?('2017-03-05'::timestamp)", expect: 2017, example: true},
]
}, {
type: :function,
name: :mysql_month,
description: "Extract the month from a datetime",
params: "ts timestamp",
return_type: "integer",
body: %~
if not ts:
return None
return ts.month
~,
tests: [
{query: "select ?('2015-01-03T04:05:06.07'::timestamp)", expect: 1, example: true},
{query: "select ?('2016-02-04T04:05:06.07 -07'::timestamp)", expect: 2, example: true},
{query: "select ?('2016-03-05'::timestamp)", expect: 3, example: true},
]
}, {
type: :function,
name: :mysql_day,
description: "Extract the day from a datetime",
params: "ts timestamp",
return_type: "integer",
body: %~
if not ts:
return None
return ts.day
~,
tests: [
{query: "select ?('2015-02-03T04:05:06.07'::timestamp)", expect: 3, example: true},
{query: "select ?('2016-02-04T04:05:06.07 -07'::timestamp)", expect: 4, example: true},
{query: "select ?('2016-02-05'::timestamp)", expect: 5, example: true},
]
}, {
type: :function,
name: :mysql_hour,
description: "Extract the hour from a datetime",
params: "ts timestamp",
return_type: "integer",
body: %~
if not ts:
return None
return ts.hour
~,
tests: [
{query: "select ?('2015-02-03T04:05:06.07'::timestamp)", expect: 4, example: true},
{query: "select ?('2016-02-03T04:05:06.07 -07'::timestamp)", expect: 4, example: true},
{query: "select ?('2016-02-03'::timestamp)", expect: 0, example: true},
]
}, {
type: :function,
name: :mysql_minute,
description: "Extract the minute from a datetime",
params: "ts timestamp",
return_type: "integer",
body: %~
if not ts:
return None
return ts.minute
~,
tests: [
{query: "select ?('2015-02-03T04:05:06.07'::timestamp)", expect: 5, example: true},
{query: "select ?('2016-02-03T04:15:06.07 -07'::timestamp)", expect: 15, example: true},
{query: "select ?('2016-02-03'::timestamp)", expect: 0, example: true},
]
}, {
type: :function,
name: :mysql_second,
description: "Extract the second from a datetime",
params: "ts timestamp",
return_type: "integer",
body: %~
if not ts:
return None
return ts.second
~,
tests: [
{query: "select ?('2015-02-03T04:05:06.07'::timestamp)", expect: 6, example: true},
{query: "select ?('2016-02-03T04:15:16.07 -07'::timestamp)", expect: 16, example: true},
{query: "select ?('2016-02-03'::timestamp)", expect: 0, example: true},
]
}, {
type: :function,
name: :mysql_yearweek,
description: "Extract the week of the year from a datetime",
params: "ts timestamp",
return_type: "varchar(max)",
body: %~
if not ts:
return None
cal = ts.isocalendar()
return str(cal[0]) + str(cal[1]).zfill(2)
~,
tests: [
{query: "select ?('2015-02-03T04:05:06.07'::timestamp)", expect: '201506', example: true},
{query: "select ?('2016-02-03T04:15:16.07 -07'::timestamp)", expect: '201605', example: true},
{query: "select ?('2016-02-03'::timestamp)", expect: '201605', example: true},
]
},
]
end
| ruby | MIT | d9cd02c9bbd5aec39a24996ac2548f96ffa5c381 | 2026-01-04T17:54:54.457515Z | false |
PeriscopeData/redshift-udfs | https://github.com/PeriscopeData/redshift-udfs/blob/d9cd02c9bbd5aec39a24996ac2548f96ffa5c381/lib/utils.rb | lib/utils.rb | class Object
def present?
!nil?
end
end
| ruby | MIT | d9cd02c9bbd5aec39a24996ac2548f96ffa5c381 | 2026-01-04T17:54:54.457515Z | false |
PeriscopeData/redshift-udfs | https://github.com/PeriscopeData/redshift-udfs/blob/d9cd02c9bbd5aec39a24996ac2548f96ffa5c381/lib/udf_number_utils.rb | lib/udf_number_utils.rb | class UdfNumberUtils
UDFS = [
{
type: :function,
name: :format_num,
description: "Format a number with Python's string format notation",
params: "num float, format varchar",
return_type: "varchar",
body: %~
if not num or not format:
return None
try:
return ("{:" + format + "}").format(num)
except ValueError:
try:
return ("{:" + format + "}").format(int(num))
except ValueError:
return None
~,
tests: [
{query: "select ?(2.17189, '.2f')", expect: '2.17', example: true},
{query: "select ?(2, '0>4d')", expect: '0002', example: true},
{query: "select ?(1234567.89, ',')", expect: '1,234,567.89', example: true},
{query: "select ?(0.1234, '.2%')", expect: '12.34%', example: true},
{query: "select ?(1, 'bonk')", expect: nil},
{query: "select ?(null, null)", expect: nil},
]
}
]
end
| ruby | MIT | d9cd02c9bbd5aec39a24996ac2548f96ffa5c381 | 2026-01-04T17:54:54.457515Z | false |
PeriscopeData/redshift-udfs | https://github.com/PeriscopeData/redshift-udfs/blob/d9cd02c9bbd5aec39a24996ac2548f96ffa5c381/lib/udf_stats.rb | lib/udf_stats.rb | class UdfStats
UDFS = [
{
type: :function,
name: :experiment_result_p_value,
description: "Returns a p-value for a controlled experiment to determine statistical significance",
params: "control_size float, control_conversion float, experiment_size float, experiment_conversion float",
return_type: "float",
body: %~
from scipy.stats import chi2_contingency
from numpy import array
observed = array([
[control_size - control_conversion, control_conversion],
[experiment_size - experiment_conversion, experiment_conversion]
])
result = chi2_contingency(observed, correction=True)
chisq, p = result[:2]
return p
~,
tests: [
{query: "select round(?(5000,486, 5000, 527),3)", expect: 0.185, example: true},
{query: "select case when ?(5000,486, 5000, 527) < 0.05 then 'yes' else 'no' end as signifcant", expect: 'no', example: true},
{query: "select ?(20000,17998,20000, 17742)", expect: 3.57722238820663e-05, example: true},
{query: "select case when ?(20000,17998,20000, 17742) < 0.05 then 'yes' else 'no' end as significant", expect: 'yes', example: true}
]
}, {
type: :function,
name: :binomial_hpdr,
description: "Returns true if a value is within the Highest Posterior Density Region",
params: "value float, successes integer, samples integer, pct float, a integer, b integer, n_pbins integer",
return_type: "integer",
body: %~
# Taken from:
# http://stackoverflow.com/a/19285227
import numpy
from scipy.stats import beta
from scipy.stats import norm
n = successes
N = samples
rv = beta(n+a, N-n+b)
stdev = rv.stats('v')**0.5
mode = (n+a-1.)/(N+a+b-2.)
n_sigma = numpy.ceil(norm.ppf( (1+pct)/2. ))+1
max_p = mode + n_sigma * stdev
if max_p > 1:
max_p = 1.
min_p = mode - n_sigma * stdev
if min_p > 1:
min_p = 1.
p_range = numpy.linspace(min_p, max_p, n_pbins+1)
if mode > 0.5:
sf = rv.sf(p_range)
pmf = sf[:-1] - sf[1:]
else:
cdf = rv.cdf(p_range)
pmf = cdf[1:] - cdf[:-1]
# find the upper and lower bounds of the interval
sorted_idxs = numpy.argsort( pmf )[::-1]
cumsum = numpy.cumsum( numpy.sort(pmf)[::-1] )
j = numpy.argmin( numpy.abs(cumsum - pct) )
upper = p_range[ (sorted_idxs[:j+1]).max()+1 ]
lower = p_range[ (sorted_idxs[:j+1]).min() ]
if (value >= lower and value <= upper):
return 0
elif value >= upper:
return 1
else:
return -1
~,
tests: [
{query: "select ?(0.7, 10, 20, .95, 1, 1, 1000)", expect: 0, example: true},
{query: "select ?(0.9, 10, 20, .95, 1, 1, 1000)", expect: 1, example: true},
{query: "select ?(0.3, 10, 20, .95, 1, 1, 1000)", expect: 0, example: true},
{query: "select ?(0.1, 10, 20, .95, 1, 1, 1000)", expect: -1, example: true}
]
}, {
type: :function,
name: :binomial_hpdr_upper,
description: "Returns the upper boundary fo the Highest Posterior Density Region",
params: "successes integer, samples integer, pct float, a integer, b integer, n_pbins integer",
return_type: "float",
body: %~
# Taken from:
# http://stackoverflow.com/a/19285227
import numpy
from scipy.stats import beta
from scipy.stats import norm
n = successes
N = samples
rv = beta(n+a, N-n+b)
stdev = rv.stats('v')**0.5
mode = (n+a-1.)/(N+a+b-2.)
n_sigma = numpy.ceil(norm.ppf( (1+pct)/2. ))+1
max_p = mode + n_sigma * stdev
if max_p > 1:
max_p = 1.
min_p = mode - n_sigma * stdev
if min_p > 1:
min_p = 1.
p_range = numpy.linspace(min_p, max_p, n_pbins+1)
if mode > 0.5:
sf = rv.sf(p_range)
pmf = sf[:-1] - sf[1:]
else:
cdf = rv.cdf(p_range)
pmf = cdf[1:] - cdf[:-1]
# find the upper and lower bounds of the interval
sorted_idxs = numpy.argsort( pmf )[::-1]
cumsum = numpy.cumsum( numpy.sort(pmf)[::-1] )
j = numpy.argmin( numpy.abs(cumsum - pct) )
return p_range[ (sorted_idxs[:j+1]).max()+1 ]
~,
tests: [
{query: "select round(?(10, 20, .95, 1, 1, 1000), 3)", expect: 0.702, example: true},
{query: "select round(?(1, 20, .95, 1, 1, 1000), 3)", expect: 0.208, example: true}
]
}, {
type: :function,
name: :binomial_hpdr_lower,
description: "Returns the lower boundary of the Highest Posterior Density Region",
params: "successes integer, samples integer, pct float, a integer, b integer, n_pbins integer",
return_type: "float",
body: %~
# Taken from:
# http://stackoverflow.com/a/19285227
import numpy
from scipy.stats import beta
from scipy.stats import norm
n = successes
N = samples
rv = beta(n+a, N-n+b)
stdev = rv.stats('v')**0.5
mode = (n+a-1.)/(N+a+b-2.)
n_sigma = numpy.ceil(norm.ppf( (1+pct)/2. ))+1
max_p = mode + n_sigma * stdev
if max_p > 1:
max_p = 1.
min_p = mode - n_sigma * stdev
if min_p > 1:
min_p = 1.
p_range = numpy.linspace(min_p, max_p, n_pbins+1)
if mode > 0.5:
sf = rv.sf(p_range)
pmf = sf[:-1] - sf[1:]
else:
cdf = rv.cdf(p_range)
pmf = cdf[1:] - cdf[:-1]
# find the upper and lower bounds of the interval
sorted_idxs = numpy.argsort( pmf )[::-1]
cumsum = numpy.cumsum( numpy.sort(pmf)[::-1] )
j = numpy.argmin( numpy.abs(cumsum - pct) )
return p_range[ (sorted_idxs[:j+1]).min() ]
~,
tests: [
{query: "select round(?(10, 20, .95, 1, 1, 1000), 3)", expect: 0.298, example: true},
{query: "select round(?(1, 20, .95, 1, 1, 1000), 3)", expect: 0.003, example: true}
]
}
]
end
| ruby | MIT | d9cd02c9bbd5aec39a24996ac2548f96ffa5c381 | 2026-01-04T17:54:54.457515Z | false |
envato-archive/aldous | https://github.com/envato-archive/aldous/blob/0eb0a18b511345ad5fea3072a7111ea5ebcfb30d/spec/spec_helper.rb | spec/spec_helper.rb | require 'aldous'
Dir[File.join(File.dirname(__FILE__), 'support', '**', "*.rb").to_s].each {|file| require file }
RSpec.configure do |config|
config.filter_run :focus
config.run_all_when_everything_filtered = true
if config.files_to_run.one?
config.default_formatter = 'doc'
end
config.profile_examples = 2
config.order = :random
Kernel.srand config.seed
config.expect_with :rspec do |expectations|
expectations.syntax = :expect
end
config.mock_with :rspec do |mocks|
mocks.syntax = :expect
mocks.verify_partial_doubles = true
end
end
| ruby | MIT | 0eb0a18b511345ad5fea3072a7111ea5ebcfb30d | 2026-01-04T17:54:58.048556Z | false |
envato-archive/aldous | https://github.com/envato-archive/aldous/blob/0eb0a18b511345ad5fea3072a7111ea5ebcfb30d/spec/aldous/dummy_logger_spec.rb | spec/aldous/dummy_logger_spec.rb | RSpec.describe Aldous::DummyLogger do
describe "::info" do
it "responds to the info method correctly" do
expect(described_class.info('blah')).to eq nil
end
end
end
| ruby | MIT | 0eb0a18b511345ad5fea3072a7111ea5ebcfb30d | 2026-01-04T17:54:58.048556Z | false |
envato-archive/aldous | https://github.com/envato-archive/aldous/blob/0eb0a18b511345ad5fea3072a7111ea5ebcfb30d/spec/aldous/controller_action_spec.rb | spec/aldous/controller_action_spec.rb | RSpec.describe Aldous::ControllerAction do
before do
class ExampleControllerAction < Aldous::ControllerAction
end
end
after do
Object.send :remove_const, 'ExampleControllerAction'
end
let(:action) {ExampleControllerAction.new(controller)}
let(:controller) {double 'controller', view_context: view_context}
let(:view_context) {double "view_context"}
describe "::build" do
before do
allow(ExampleControllerAction).to receive(:new).and_return(action)
allow(Aldous::Controller::Action::Wrapper).to receive(:new)
end
it "wraps a controller action instance" do
expect(Aldous::Controller::Action::Wrapper).to receive(:new).with(action)
ExampleControllerAction.build(controller)
end
end
describe "::perform" do
let(:wrapper) {double "wrapper", perform: nil}
before do
allow(ExampleControllerAction).to receive(:new).and_return(action)
allow(Aldous::Controller::Action::Wrapper).to receive(:new).and_return(wrapper)
end
it "calls perform on the wrapper" do
expect(wrapper).to receive(:perform)
ExampleControllerAction.perform(controller)
end
end
describe "::inherited" do
context "a controller action instance" do
Aldous.configuration.controller_methods_exposed_to_action.each do |method_name|
it "responds to #{method_name}" do
expect(action).to respond_to method_name
end
end
end
end
describe "#perform" do
it "raises an error since it should be overridden" do
expect{action.perform}.to raise_error
end
end
describe "#default_view_data" do
it "is a blank hash by default" do
expect(action.default_view_data).to eq Hash.new
end
end
describe "#preconditions" do
it "is a blank array by default" do
expect(action.preconditions).to eq []
end
end
describe "#default_error_handler" do
it "is a blank html view by default" do
expect(action.default_error_handler('foo')).to eq Aldous::View::Blank::HtmlView
end
end
end
| ruby | MIT | 0eb0a18b511345ad5fea3072a7111ea5ebcfb30d | 2026-01-04T17:54:58.048556Z | false |
envato-archive/aldous | https://github.com/envato-archive/aldous/blob/0eb0a18b511345ad5fea3072a7111ea5ebcfb30d/spec/aldous/logging_wrapper_spec.rb | spec/aldous/logging_wrapper_spec.rb | RSpec.describe Aldous::LoggingWrapper do
describe "::log" do
subject(:log) {described_class.log(error)}
let(:error) {"hello world"}
let(:aldous_config) {
double "aldous_config", error_reporter: error_reporter, logger: logger
}
let(:error_reporter) {double "error_reporter", report: nil}
let(:logger) {double "logger", info: nil}
before do
allow(Aldous).to receive(:config).and_return(aldous_config)
end
context "when error is a string" do
let(:error) {"hello world"}
it "reports the error" do
expect(error_reporter).to receive(:report).with(error)
log
end
it "logs the error" do
expect(logger).to receive(:info).with(error)
log
end
end
context "when error is an error object" do
let(:error) {RuntimeError.new(message)}
let(:message) {"hello"}
let(:backtrace) {"foobar"}
before do
error.set_backtrace(backtrace)
end
it "reports the error message" do
expect(error_reporter).to receive(:report).with(error)
log
end
it "logs the error message" do
expect(logger).to receive(:info).with(message)
log
end
it "logs the error backtrace" do
expect(logger).to receive(:info).with(backtrace)
log
end
end
end
end
| ruby | MIT | 0eb0a18b511345ad5fea3072a7111ea5ebcfb30d | 2026-01-04T17:54:58.048556Z | false |
envato-archive/aldous | https://github.com/envato-archive/aldous/blob/0eb0a18b511345ad5fea3072a7111ea5ebcfb30d/spec/aldous/configuration_spec.rb | spec/aldous/configuration_spec.rb | RSpec.describe Aldous::Configuration do
subject(:config) {described_class.new}
describe "#error_reporter" do
it "is configured to use the dummy error reporter by default" do
expect(config.error_reporter).to eq ::Aldous::DummyErrorReporter
end
end
describe "#logger" do
it "is configured to use the stdout logger by default" do
expect(config.logger).to eq ::Aldous::StdoutLogger
end
end
end
| ruby | MIT | 0eb0a18b511345ad5fea3072a7111ea5ebcfb30d | 2026-01-04T17:54:58.048556Z | false |
envato-archive/aldous | https://github.com/envato-archive/aldous/blob/0eb0a18b511345ad5fea3072a7111ea5ebcfb30d/spec/aldous/controller_spec.rb | spec/aldous/controller_spec.rb | RSpec.describe Aldous::Controller do
before do
class ExampleController
include Aldous::Controller
end
end
describe "::controller_actions" do
before do
ExampleController.controller_actions(:hello, :world)
end
context "a controller instance" do
let(:controller) {ExampleController.new}
it "responds to :hello" do
expect(controller).to respond_to :hello
end
it "responds to :world" do
expect(controller).to respond_to :world
end
end
end
end
| ruby | MIT | 0eb0a18b511345ad5fea3072a7111ea5ebcfb30d | 2026-01-04T17:54:58.048556Z | false |
envato-archive/aldous | https://github.com/envato-archive/aldous/blob/0eb0a18b511345ad5fea3072a7111ea5ebcfb30d/spec/aldous/service_spec.rb | spec/aldous/service_spec.rb | describe Aldous::Service do
before do
class ExampleService < Aldous::Service
end
end
after do
Object.send :remove_const, 'ExampleService'
end
describe '.build' do
subject(:build) { ExampleService.build argument }
let(:argument) { 'argument' }
let(:service) { instance_double ExampleService }
before do
allow(ExampleService).to receive(:new) { service }
end
it 'instantiates a new service with arguments' do
expect(ExampleService).to receive(:new).with(argument)
build
end
it 'instantiates a service wrapper with service' do
expect(Aldous::Service::Wrapper).to receive(:new).with(service)
build
end
end
describe '.perform' do
subject(:perform) { ExampleService.perform argument }
let(:argument) { 'argument' }
let(:wrapper) { instance_double Aldous::Service::Wrapper, perform: nil }
before do
allow(ExampleService).to receive(:build) { wrapper }
end
it 'builds wrapper with arguments' do
expect(ExampleService).to receive(:build).with(argument)
perform
end
it 'calls perform on the wrapper' do
expect(wrapper).to receive(:perform)
perform
end
end
describe '.perform!' do
subject(:perform!) { ExampleService.perform! argument }
let(:argument) { 'argument' }
let(:wrapper) { instance_double Aldous::Service::Wrapper, perform!: nil }
before do
allow(ExampleService).to receive(:build) { wrapper }
end
it 'builds wrapper with arguments' do
expect(ExampleService).to receive(:build).with(argument)
perform!
end
it 'calls perform! on the wrapper' do
expect(wrapper).to receive(:perform!)
perform!
end
end
describe '#perform' do
let(:service) { ExampleService.new }
subject(:perform) { service.perform }
it 'raises a NotImplementedError' do
expect { perform }.to raise_error(NotImplementedError, "ExampleService must implement method #perform")
end
end
describe '#raisable_error' do
let(:service) { ExampleService.new }
subject(:raisable_error) { service.raisable_error }
it 'defaults to Aldous::Errors::UserError' do
expect(raisable_error).to eq Aldous::Errors::UserError
end
end
describe '#default_result_data' do
let(:service) { ExampleService.new }
subject(:default_result_data) { service.default_result_data }
it 'defaults to {}' do
expect(default_result_data).to eq({})
end
end
end
| ruby | MIT | 0eb0a18b511345ad5fea3072a7111ea5ebcfb30d | 2026-01-04T17:54:58.048556Z | false |
envato-archive/aldous | https://github.com/envato-archive/aldous/blob/0eb0a18b511345ad5fea3072a7111ea5ebcfb30d/spec/aldous/params_spec.rb | spec/aldous/params_spec.rb | RSpec.describe Aldous::Params do
describe "::build" do
it "instantiates a new params object" do
expect(described_class).to receive(:new)
described_class.build({})
end
end
describe "#fetch" do
let(:params_object) {described_class.new(params)}
let(:params) { {} }
context "when error occurs" do
before do
allow(params_object).to receive(:permitted_params).and_raise(RuntimeError.new)
allow(Aldous::LoggingWrapper).to receive(:log)
end
it "logs the error" do
expect(Aldous::LoggingWrapper).to receive(:log)
params_object.fetch
end
it "returns nil" do
expect(params_object.fetch).to be_nil
end
end
context "when no error occurs" do
before do
allow(params_object).to receive(:permitted_params).and_return('hello')
end
it "returns the permitted_params" do
expect(params_object.fetch).to eq 'hello'
end
end
end
end
| ruby | MIT | 0eb0a18b511345ad5fea3072a7111ea5ebcfb30d | 2026-01-04T17:54:58.048556Z | false |
envato-archive/aldous | https://github.com/envato-archive/aldous/blob/0eb0a18b511345ad5fea3072a7111ea5ebcfb30d/spec/aldous/view_builder_spec.rb | spec/aldous/view_builder_spec.rb | RSpec.describe Aldous::ViewBuilder do
let(:view_builder) { described_class.new(view_context, default_view_data) }
let(:view_context) { double "view_context" }
let(:default_view_data) { {hello: 1} }
let(:respondable_class) { double "respondable_class"}
let(:extra_data) { {world: 2} }
let(:status) { :foo }
let(:simple_dto) {instance_double(Aldous::SimpleDto)}
let(:respondable_instance) {double "respondable_instance"}
describe "#build" do
subject(:build) {view_builder.build(respondable_class, extra_data)}
let(:view_data) { {hello: 1, world: 2} }
before do
allow(Aldous::SimpleDto).to receive(:new).and_return(simple_dto)
allow(respondable_class).to receive(:new).and_return(respondable_instance)
end
context "when status is part of the extra_data" do
let(:extra_data) { {world: 2, status: status} }
it "creates a dto with the correct data" do
expect(Aldous::SimpleDto).to receive(:new).with(view_data).and_return(simple_dto)
build
end
end
it "creates a dto with the correct data" do
expect(Aldous::SimpleDto).to receive(:new).with(view_data).and_return(simple_dto)
build
end
it "returns a respondable instance" do
expect(respondable_class).to receive(:new).with(nil, simple_dto, view_context)
build
end
end
end
| ruby | MIT | 0eb0a18b511345ad5fea3072a7111ea5ebcfb30d | 2026-01-04T17:54:58.048556Z | false |
envato-archive/aldous | https://github.com/envato-archive/aldous/blob/0eb0a18b511345ad5fea3072a7111ea5ebcfb30d/spec/aldous/simple_dto_spec.rb | spec/aldous/simple_dto_spec.rb | RSpec.describe Aldous::SimpleDto do
let(:dto) {described_class.new(data)}
let(:data) {Hash.new}
context "errors passed in are available as errors list" do
let(:data) { {errors: 'hello'} }
it "can get the right error" do
expect(dto.errors.first).to eq 'hello'
end
end
context "messages passed in are available as messages list" do
let(:data) { {messages: 'hello'} }
it "can get the right message" do
expect(dto.messages.first).to eq 'hello'
end
end
context "all data passed in is available to get it out again" do
let(:data) { {hello: 1} }
it "can get access to the original data" do
expect(dto._data).to eq data
end
end
context "all keys passed in are available via accessors" do
let(:data) { {foo: 1, bar: 2} }
it "can get :foo via method" do
expect(dto.foo).to eq 1
end
it "can get :bar via method" do
expect(dto.bar).to eq 2
end
end
end
| ruby | MIT | 0eb0a18b511345ad5fea3072a7111ea5ebcfb30d | 2026-01-04T17:54:58.048556Z | false |
envato-archive/aldous | https://github.com/envato-archive/aldous/blob/0eb0a18b511345ad5fea3072a7111ea5ebcfb30d/spec/aldous/dummy_error_reporter_spec.rb | spec/aldous/dummy_error_reporter_spec.rb | RSpec.describe Aldous::DummyErrorReporter do
describe "::report" do
let(:error) {RuntimeError.new('blah')}
let(:data) { Hash.new }
it "responds to the report method correctly" do
expect(described_class.report(error, data)).to eq nil
end
end
end
| ruby | MIT | 0eb0a18b511345ad5fea3072a7111ea5ebcfb30d | 2026-01-04T17:54:58.048556Z | false |
envato-archive/aldous | https://github.com/envato-archive/aldous/blob/0eb0a18b511345ad5fea3072a7111ea5ebcfb30d/spec/aldous/controller/action_execution_service_spec.rb | spec/aldous/controller/action_execution_service_spec.rb | RSpec.describe Aldous::Controller::ActionExecutionService do
let(:action_execution_service) {described_class.new(controller, controller_action_class)}
let(:controller) {double "controller", head: nil, performed?: false}
let(:controller_action_class) {double "controller_action_class", build: action}
let(:action) {double 'action', perform: action_result, default_view_data: default_view_data}
let(:action_result) {'foobar'}
let(:default_view_data) {'hello'}
describe "::perform" do
subject(:perform) {described_class.perform(controller, controller_action_class)}
let(:action_execution_service) {double "action_execution_service", perform: nil}
before do
allow(described_class).to receive(:new).and_return(action_execution_service)
end
it "instantiates the action execution service" do
expect(described_class).to receive(:new).with(controller, controller_action_class)
perform
end
it "performs the action execution service" do
expect(action_execution_service).to receive(:perform)
perform
end
end
describe "#perform" do
subject(:perform) {action_execution_service.perform}
let(:preconditions_execution_service) {double "preconditions_execution_service", perform: preconditions_result}
let(:preconditions_result) {[nil, nil]}
before do
allow(Aldous::Controller::PreconditionsExecutionService).to receive(:new).and_return(preconditions_execution_service)
allow(Aldous::Controller::Action::ResultExecutionService).to receive(:perform)
end
context "when preconditions did not halt execution" do
it "executes the result with action_result" do
expect(Aldous::Controller::Action::ResultExecutionService).to receive(:perform).with(controller, action_result, default_view_data)
perform
end
context "but action perform halted execution due to render" do
before do
allow(controller).to receive(:performed?).and_return(false, true)
end
it "returns nil" do
expect(perform).to be_nil
end
it "does not execute the result" do
expect(Aldous::Controller::Action::ResultExecutionService).to_not receive(:perform)
perform
end
end
end
context "when preconditions did halt execution" do
let(:preconditions_result) {[precondition, precondition_result]}
let(:precondition) {double 'precondition', perform: precondition_result, default_view_data: default_view_data}
let(:precondition_result) {'preconditionfoobar'}
let(:default_view_data) {'precondtionhello'}
it "executes the result with precondition_result" do
expect(Aldous::Controller::Action::ResultExecutionService).to receive(:perform).with(controller, precondition_result, default_view_data)
perform
end
context "via a render on the controller object" do
let(:controller) {double "controller", head: nil, performed?: true}
it "returns nil" do
expect(perform).to be_nil
end
it "does not execute the result" do
expect(Aldous::Controller::Action::ResultExecutionService).to_not receive(:perform)
perform
end
end
end
context "when error occurs" do
before do
allow(Aldous::LoggingWrapper).to receive(:log)
allow(Aldous::Controller::PreconditionsExecutionService).to receive(:new).and_raise
end
it "logs the error" do
expect(Aldous::LoggingWrapper).to receive(:log)
perform
end
it "returns a 500 via controller" do
expect(controller).to receive(:head).with(:internal_server_error)
perform
end
end
end
end
| ruby | MIT | 0eb0a18b511345ad5fea3072a7111ea5ebcfb30d | 2026-01-04T17:54:58.048556Z | false |
envato-archive/aldous | https://github.com/envato-archive/aldous/blob/0eb0a18b511345ad5fea3072a7111ea5ebcfb30d/spec/aldous/controller/preconditions_execution_service_spec.rb | spec/aldous/controller/preconditions_execution_service_spec.rb | RSpec.describe Aldous::Controller::PreconditionsExecutionService do
let(:preconditions_execution_service) {described_class.new(action_wrapper, controller)}
let(:controller) {double "controller"}
let(:action_wrapper) {double 'action wrapper', preconditions: preconditions, controller_action: action}
let(:action) {double 'action', view_builder: view_builder}
let(:view_builder) {double 'view_builder'}
let(:preconditions) { [] }
describe "#perform" do
subject(:perform) {preconditions_execution_service.perform}
context "when no preconditions defined" do
it "returns an array of nils" do
expect(perform).to eq [nil, nil]
end
end
context "when preconditions defined" do
let(:preconditions) { [precondition_class] }
let(:precondition_class) {double 'precondition_class', build: precondition}
let(:precondition) {double "precondition", perform: nil}
it "builds the precondition with the controller_action" do
expect(precondition_class).to receive(:build).with(action, controller, view_builder)
perform
end
context "but they don't short-circuit execution" do
it "returns an array of nils" do
expect(perform).to eq [nil, nil]
end
end
context "and they short-circuit execution" do
let(:precondition) {double "precondition", perform: precondition_result}
let(:precondition_result) {Aldous::Respondable::Renderable.new(nil, nil, nil)}
it "returns an array of precondition and precondition result" do
expect(perform).to eq [precondition, precondition_result]
end
end
end
end
end
| ruby | MIT | 0eb0a18b511345ad5fea3072a7111ea5ebcfb30d | 2026-01-04T17:54:58.048556Z | false |
envato-archive/aldous | https://github.com/envato-archive/aldous/blob/0eb0a18b511345ad5fea3072a7111ea5ebcfb30d/spec/aldous/controller/action/precondition_spec.rb | spec/aldous/controller/action/precondition_spec.rb | RSpec.describe Aldous::Controller::Action::Precondition do
before do
class ExamplePrecondition < Aldous::Controller::Action::Precondition
end
end
after do
Object.send :remove_const, 'ExamplePrecondition'
end
let(:precondition) {ExamplePrecondition.new(action, controller, view_builder)}
let(:action) {double 'action', controller: controller, default_view_data: default_view_data}
let(:controller) {double 'controller', view_context: view_context}
let(:view_builder) {double 'view_builder'}
let(:view_context) {double "view_context"}
let(:default_view_data) {double "default_view_data"}
describe "::build" do
before do
allow(ExamplePrecondition).to receive(:new).and_return(precondition)
allow(Aldous::Controller::Action::Precondition::Wrapper).to receive(:new)
end
it "wraps a controller action instance" do
expect(Aldous::Controller::Action::Precondition::Wrapper).to receive(:new).with(precondition)
ExamplePrecondition.build(action, controller, view_builder)
end
end
describe "::perform" do
let(:wrapper) {double "wrapper", perform: nil}
before do
allow(ExamplePrecondition).to receive(:new).and_return(action)
allow(Aldous::Controller::Action::Precondition::Wrapper).to receive(:new).and_return(wrapper)
end
it "calls perform on the wrapper" do
expect(wrapper).to receive(:perform)
ExamplePrecondition.perform(action, controller, view_builder)
end
end
describe "::inherited" do
context "a precondition instance" do
Aldous.configuration.controller_methods_exposed_to_action.each do |method_name|
it "responds to #{method_name}" do
expect(precondition).to respond_to method_name
end
end
end
end
describe "#perform" do
it "raises an error since it should be overridden" do
expect{precondition.perform}.to raise_error
end
end
end
| ruby | MIT | 0eb0a18b511345ad5fea3072a7111ea5ebcfb30d | 2026-01-04T17:54:58.048556Z | false |
envato-archive/aldous | https://github.com/envato-archive/aldous/blob/0eb0a18b511345ad5fea3072a7111ea5ebcfb30d/spec/aldous/controller/action/result_execution_service_spec.rb | spec/aldous/controller/action/result_execution_service_spec.rb | RSpec.describe Aldous::Controller::Action::ResultExecutionService do
let(:result_execution_service) {described_class.new(controller, respondable, default_view_data)}
let(:controller) {double "controller", view_context: view_context}
let(:view_context) {double "view_context"}
let(:respondable) do
double "respondable", {
action: action
}
end
let(:default_view_data) { {hello: 'world'} }
let(:action) {double 'action', execute: nil}
describe "::perform" do
subject(:perform) {described_class.perform(controller, respondable, default_view_data)}
let(:result_execution_service) {double "result_execution_service", perform: nil}
before do
allow(described_class).to receive(:new).and_return(result_execution_service)
end
it "instantiates the result execution service" do
expect(described_class).to receive(:new).with(controller, respondable, default_view_data)
perform
end
it "performs the result execution service" do
expect(result_execution_service).to receive(:perform)
perform
end
end
describe "#perform" do
subject(:perform) {result_execution_service.perform}
it "fetches the action from the complete respondable" do
expect(respondable).to receive(:action).with(controller)
perform
end
it "executes the complete respondable action" do
expect(action).to receive(:execute)
perform
end
end
end
| ruby | MIT | 0eb0a18b511345ad5fea3072a7111ea5ebcfb30d | 2026-01-04T17:54:58.048556Z | false |
envato-archive/aldous | https://github.com/envato-archive/aldous/blob/0eb0a18b511345ad5fea3072a7111ea5ebcfb30d/spec/aldous/controller/action/wrapper_spec.rb | spec/aldous/controller/action/wrapper_spec.rb | RSpec.describe Aldous::Controller::Action::Wrapper do
let(:wrapper) { described_class.new controller_action }
let(:controller_action) { double 'controller action',
default_view_data: default_view_data,
preconditions: preconditions,
default_error_handler: default_error_handler,
view_builder: view_builder,
perform: nil }
let(:default_view_data) { {default_view_data: true} }
let(:preconditions) { double 'preconditions' }
let(:default_error_handler) {double 'default_error_handler'}
let(:view_builder) {double 'view_builder'}
before do
allow(Aldous::LoggingWrapper).to receive(:log)
end
describe '#perform' do
subject(:perform) { wrapper.perform }
it "calls perform on the controller action" do
expect(controller_action).to receive(:perform)
perform
end
context 'when controller service throws an exception' do
let(:e) { StandardError.new 'message' }
before do
allow(controller_action).to receive(:perform).and_raise(e)
end
it 'reports the error' do
expect(Aldous::LoggingWrapper).to receive(:log).with(e)
perform
end
context "and the default error handler is a respondable" do
let(:default_error_handler) {Aldous::Respondable::Renderable}
it "builds a default error view with errors" do
expect(view_builder).to receive(:build).with(default_error_handler, errors: [e])
perform
end
end
context "and the default error handler is not a respondable" do
it "doesn't need to do anything" do
expect(default_error_handler).to_not receive(:build)
perform
end
end
end
end
end
| ruby | MIT | 0eb0a18b511345ad5fea3072a7111ea5ebcfb30d | 2026-01-04T17:54:58.048556Z | false |
envato-archive/aldous | https://github.com/envato-archive/aldous/blob/0eb0a18b511345ad5fea3072a7111ea5ebcfb30d/spec/aldous/controller/action/precondition/wrapper_spec.rb | spec/aldous/controller/action/precondition/wrapper_spec.rb | RSpec.describe Aldous::Controller::Action::Precondition::Wrapper do
let(:wrapper) { described_class.new precondition }
let(:precondition) {double 'precondition',
action: controller_action,
view_builder: view_builder,
perform: nil }
let(:controller_action) { double 'controller action',
default_view_data: default_view_data,
default_error_handler: default_error_handler,
view_builder: view_builder,
perform: nil }
let(:default_view_data) { {default_view_data: true} }
let(:default_error_handler) {double 'default_error_handler'}
let(:view_builder) {double 'view_builder'}
before do
allow(Aldous::LoggingWrapper).to receive(:log)
end
describe '#perform' do
subject(:perform) { wrapper.perform }
it "calls perform on the precondition" do
expect(precondition).to receive(:perform)
perform
end
context 'when precondition throws an exception' do
let(:e) { StandardError.new 'message' }
before do
allow(precondition).to receive(:perform).and_raise(e)
end
context "when the default error handler is not a respondable" do
it "calls the default error handler" do
allow(controller_action).to receive(:default_error_handler).with(e)
perform
end
end
context "when the default error handler is a respondable" do
let(:default_error_handler) {Aldous::Respondable::Renderable}
it "builds the default error handler" do
allow(view_builder).to receive(:build).with(default_error_handler, errors: [e])
perform
end
end
it 'reports the error' do
expect(Aldous::LoggingWrapper).to receive(:log).with(e)
perform
end
end
end
end
| ruby | MIT | 0eb0a18b511345ad5fea3072a7111ea5ebcfb30d | 2026-01-04T17:54:58.048556Z | false |
envato-archive/aldous | https://github.com/envato-archive/aldous/blob/0eb0a18b511345ad5fea3072a7111ea5ebcfb30d/spec/aldous/service/wrapper_spec.rb | spec/aldous/service/wrapper_spec.rb | RSpec.describe Aldous::Service::Wrapper do
let(:wrapper) { described_class.new service }
let(:service) { double 'service', perform: service_result, default_result_data: default_result_data, raisable_error: raisable_error }
let(:service_result) { Aldous::Service::Result::Success.new service_result_data }
let(:default_result_data) { { default_result_data: true } }
let(:service_result_data) { { service_result_data: true } }
let(:raisable_error) { Aldous::Errors::UserError }
before do
allow(Aldous.config.error_reporter).to receive(:report)
end
describe '#perform!' do
subject(:perform!) { wrapper.perform! }
it 'calls perform on the service' do
expect(service).to receive(:perform)
perform!
end
it 'returns a result of same type as result returned by service' do
expect(perform!.class).to be service_result.class
end
it 'includes default result data in result' do
expect(perform!.default_result_data).to eq true
end
it 'includes service result data in result' do
expect(perform!.service_result_data).to eq true
end
context 'when service returns a value that is not an Aldous result' do
let(:service_result) { 'uh oh' }
it 'raises raisable error' do
expect { perform! }.to raise_error(raisable_error, "Return value of #perform must be a type of #{::Aldous::Service::Result::Base}")
end
end
context 'when service raises an error' do
let(:e) { StandardError.new 'message' }
before do
allow(service).to receive(:perform).and_raise(e)
end
it 'raises raisable error with original error message' do
expect { perform! }.to raise_error(raisable_error, e.message)
end
end
end
describe '#perform' do
subject(:perform) { wrapper.perform }
before do
Aldous.configuration.logger = Aldous::DummyLogger
end
context 'when perform! does not raise an error' do
let(:result) { Aldous::Service::Result::Success.new }
before do
allow(wrapper).to receive(:perform!) { result }
end
it 'returns the result' do
expect(perform).to eq result
end
end
context 'when perform! raises an error' do
let(:e) { raisable_error.new }
before do
allow(wrapper).to receive(:perform!).and_raise(e)
end
it 'returns a failure result' do
expect(perform).to be_failure
end
it 'includes default result data in result' do
expect(perform.default_result_data).to eq true
end
it 'includes error in result' do
expect(perform.errors).to eq [e]
end
it 'reports the error' do
expect(Aldous::LoggingWrapper).to receive(:log).with(e)
perform
end
context 'when error cause is another error' do
let(:cause) { StandardError.new }
before do
allow(e).to receive(:cause) { cause }
end
it 'reports the error cause' do
expect(Aldous::LoggingWrapper).to receive(:log).with(cause)
perform
end
end
end
end
end
| ruby | MIT | 0eb0a18b511345ad5fea3072a7111ea5ebcfb30d | 2026-01-04T17:54:58.048556Z | false |
envato-archive/aldous | https://github.com/envato-archive/aldous/blob/0eb0a18b511345ad5fea3072a7111ea5ebcfb30d/spec/aldous/service/result/success_spec.rb | spec/aldous/service/result/success_spec.rb | RSpec.describe Aldous::Service::Result::Success do
subject(:result) {described_class.new}
describe "#failure?" do
it {expect(result.failure?).to eq false}
end
describe "#success?" do
it {expect(result.success?).to eq true}
end
end
| ruby | MIT | 0eb0a18b511345ad5fea3072a7111ea5ebcfb30d | 2026-01-04T17:54:58.048556Z | false |
envato-archive/aldous | https://github.com/envato-archive/aldous/blob/0eb0a18b511345ad5fea3072a7111ea5ebcfb30d/spec/aldous/service/result/failure_spec.rb | spec/aldous/service/result/failure_spec.rb | RSpec.describe Aldous::Service::Result::Failure do
subject(:result) {described_class.new}
describe "#failure?" do
it {expect(result.failure?).to eq true}
end
describe "#success?" do
it {expect(result.success?).to eq false}
end
end
| ruby | MIT | 0eb0a18b511345ad5fea3072a7111ea5ebcfb30d | 2026-01-04T17:54:58.048556Z | false |
envato-archive/aldous | https://github.com/envato-archive/aldous/blob/0eb0a18b511345ad5fea3072a7111ea5ebcfb30d/spec/aldous/view/blank/atom_view_spec.rb | spec/aldous/view/blank/atom_view_spec.rb | RSpec.describe Aldous::View::Blank::AtomView do
subject(:view) {described_class.new(status, view_data, view_context)}
let(:status) {nil}
let(:view_data) {double("result")}
let(:view_context) {double("view context")}
it "inherits from Renderable" do
expect(described_class.ancestors.include?(Aldous::Respondable::Renderable)).to be_truthy
end
it "implements the 'template' method" do
expect{ view.template }.to_not raise_error
end
end
| ruby | MIT | 0eb0a18b511345ad5fea3072a7111ea5ebcfb30d | 2026-01-04T17:54:58.048556Z | false |
envato-archive/aldous | https://github.com/envato-archive/aldous/blob/0eb0a18b511345ad5fea3072a7111ea5ebcfb30d/spec/aldous/view/blank/html_view_spec.rb | spec/aldous/view/blank/html_view_spec.rb | RSpec.describe Aldous::View::Blank::HtmlView do
subject(:view) {described_class.new(status, view_data, view_context)}
let(:status) {nil}
let(:view_data) {double("result")}
let(:view_context) {double("view context")}
it "inherits from Renderable" do
expect(described_class.ancestors.include?(Aldous::Respondable::Renderable)).to be_truthy
end
it "implements the 'template' method" do
expect{ view.template }.to_not raise_error
end
end
| ruby | MIT | 0eb0a18b511345ad5fea3072a7111ea5ebcfb30d | 2026-01-04T17:54:58.048556Z | false |
envato-archive/aldous | https://github.com/envato-archive/aldous/blob/0eb0a18b511345ad5fea3072a7111ea5ebcfb30d/spec/aldous/view/blank/json_view_spec.rb | spec/aldous/view/blank/json_view_spec.rb | RSpec.describe Aldous::View::Blank::JsonView do
subject(:view) {described_class.new(status, view_data, view_context)}
let(:status) {nil}
let(:view_data) {double("result")}
let(:view_context) {double("view context")}
it "inherits from Renderable" do
expect(described_class.ancestors.include?(Aldous::Respondable::Renderable)).to be_truthy
end
it "implements the 'template' method" do
expect{ view.template }.to_not raise_error
end
end
| ruby | MIT | 0eb0a18b511345ad5fea3072a7111ea5ebcfb30d | 2026-01-04T17:54:58.048556Z | false |
envato-archive/aldous | https://github.com/envato-archive/aldous/blob/0eb0a18b511345ad5fea3072a7111ea5ebcfb30d/spec/aldous/respondable/headable_spec.rb | spec/aldous/respondable/headable_spec.rb | RSpec.describe Aldous::Respondable::Headable do
subject(:headable) {described_class.new(status, view_data, view_context)}
let(:status) {:foo}
let(:view_data) {double("view_data")}
let(:view_context) {double("view context")}
describe "::action" do
let(:controller) {double("controller")}
it "returns a head response action object" do
expect(headable.action(controller)).to be_kind_of Aldous::Respondable::Headable::HeadAction
end
it 'creates a head response action with the relevant parameters' do
expect(Aldous::Respondable::Headable::HeadAction).to receive(:new).with(controller, status)
headable.action(controller)
end
end
end
| ruby | MIT | 0eb0a18b511345ad5fea3072a7111ea5ebcfb30d | 2026-01-04T17:54:58.048556Z | false |
envato-archive/aldous | https://github.com/envato-archive/aldous/blob/0eb0a18b511345ad5fea3072a7111ea5ebcfb30d/spec/aldous/respondable/renderable_spec.rb | spec/aldous/respondable/renderable_spec.rb | RSpec.describe Aldous::Respondable::Renderable do
class Aldous::Respondable::Renderable::Dummy < described_class
def template_data
{
locals: {hello: 1}
}
end
def default_template_locals
{
hello: 2
}
end
end
subject(:renderable) {Aldous::Respondable::Renderable::Dummy.new(status, view_data, view_context)}
let(:status) {:foo}
let(:view_data) {double("view_data")}
let(:view_context) {double("view context")}
describe "#action" do
let(:controller) {double("controller")}
it "returns a render response action object" do
expect(renderable.action(controller)).to be_kind_of Aldous::Respondable::Renderable::RenderAction
end
it 'creates a redirect response action with the relevant parameters' do
expect(Aldous::Respondable::Renderable::RenderAction).to receive(:new).with(renderable.template, status, controller, view_data)
renderable.action(controller)
end
end
describe "#template" do
subject(:renderable) {Aldous::Respondable::Renderable::Dummy.new(status, view_data, view_context)}
it "overrides the default locals with the template locals" do
expect(renderable.template).to eq({locals: {hello: 1}})
end
it "overrides the template locals with the provided locals" do
expect(renderable.template(hello: 3)).to eq({locals: {hello: 3}})
end
end
end
| ruby | MIT | 0eb0a18b511345ad5fea3072a7111ea5ebcfb30d | 2026-01-04T17:54:58.048556Z | false |
envato-archive/aldous | https://github.com/envato-archive/aldous/blob/0eb0a18b511345ad5fea3072a7111ea5ebcfb30d/spec/aldous/respondable/redirectable_spec.rb | spec/aldous/respondable/redirectable_spec.rb | RSpec.describe Aldous::Respondable::Redirectable do
class Aldous::Respondable::Redirectable::Dummy < described_class
def location
'hello'
end
end
subject(:redirectable) {Aldous::Respondable::Redirectable::Dummy.new(status, view_data, view_context)}
let(:status) {:foo}
let(:view_data) {double("view_data")}
let(:view_context) {double("view context")}
describe "::action" do
let(:controller) {double("controller")}
it "returns a redirect response action object" do
expect(redirectable.action(controller)).to be_kind_of Aldous::Respondable::Redirectable::RedirectAction
end
it 'creates a redirect response action with the relevant parameters' do
expect(Aldous::Respondable::Redirectable::RedirectAction).to receive(:new).with(redirectable.location, controller, view_data, status)
redirectable.action(controller)
end
end
end
| ruby | MIT | 0eb0a18b511345ad5fea3072a7111ea5ebcfb30d | 2026-01-04T17:54:58.048556Z | false |
envato-archive/aldous | https://github.com/envato-archive/aldous/blob/0eb0a18b511345ad5fea3072a7111ea5ebcfb30d/spec/aldous/respondable/send_data_spec.rb | spec/aldous/respondable/send_data_spec.rb | RSpec.describe Aldous::Respondable::SendData do
class Aldous::Respondable::SendData::Dummy < described_class
def data
'hello'
end
def options
'world'
end
end
subject(:send_data) {Aldous::Respondable::SendData::Dummy.new(status, view_data, view_context)}
let(:status) {:foo}
let(:view_data) {double("view_data")}
let(:view_context) {double("view context")}
describe "::action" do
let(:controller) {double("controller")}
it "returns a send_data response action object" do
expect(send_data.action(controller)).to be_kind_of Aldous::Respondable::SendData::SendDataAction
end
it 'creates a send_data response action with the relevant parameters' do
expect(Aldous::Respondable::SendData::SendDataAction).to receive(:new).with(send_data.data, send_data.options, controller, view_data)
send_data.action(controller)
end
end
end
| ruby | MIT | 0eb0a18b511345ad5fea3072a7111ea5ebcfb30d | 2026-01-04T17:54:58.048556Z | false |
envato-archive/aldous | https://github.com/envato-archive/aldous/blob/0eb0a18b511345ad5fea3072a7111ea5ebcfb30d/spec/aldous/respondable/base_spec.rb | spec/aldous/respondable/base_spec.rb | RSpec.describe Aldous::Respondable::Base do
let(:status) {:foo}
let(:view_data) {double("view_data")}
let(:view_context) {double("view context")}
describe "::new" do
it "object can be instantiated with the right params" do
expect{described_class.new(status, view_data, view_context)}.to_not raise_error
end
end
end
| ruby | MIT | 0eb0a18b511345ad5fea3072a7111ea5ebcfb30d | 2026-01-04T17:54:58.048556Z | false |
envato-archive/aldous | https://github.com/envato-archive/aldous/blob/0eb0a18b511345ad5fea3072a7111ea5ebcfb30d/spec/aldous/respondable/request_http_basic_authentication_spec.rb | spec/aldous/respondable/request_http_basic_authentication_spec.rb | ruby | MIT | 0eb0a18b511345ad5fea3072a7111ea5ebcfb30d | 2026-01-04T17:54:58.048556Z | false | |
envato-archive/aldous | https://github.com/envato-archive/aldous/blob/0eb0a18b511345ad5fea3072a7111ea5ebcfb30d/spec/aldous/respondable/redirectable/redirect_action_spec.rb | spec/aldous/respondable/redirectable/redirect_action_spec.rb | RSpec.describe Aldous::Respondable::Redirectable::RedirectAction do
subject(:respondable) {described_class.new(location, controller, view_data, status)}
let(:location) {"hello"}
let(:controller) {double 'controller', redirect_to: nil, flash: flash }
let(:view_data) {"blah"}
let(:response_status) {'world'}
let(:status) { :found }
let(:flash) { double("flash") }
let(:flash_object) { instance_double Aldous::Respondable::Shared::Flash, set_error: nil }
describe "#execute" do
before do
allow(Aldous::Respondable::Shared::Flash).to receive(:new){ flash_object }
end
it "calls redirect_to on controller with the relevant options" do
expect(controller).to receive(:redirect_to).with(location, {status: status})
respondable.execute
end
it "tries to set flash" do
expect(Aldous::Respondable::Shared::Flash).to receive(:new).with(view_data, flash)
respondable.execute
end
it "calls set_error on flash object" do
expect(flash_object).to receive(:set_error)
respondable.execute
end
end
end
| ruby | MIT | 0eb0a18b511345ad5fea3072a7111ea5ebcfb30d | 2026-01-04T17:54:58.048556Z | false |
envato-archive/aldous | https://github.com/envato-archive/aldous/blob/0eb0a18b511345ad5fea3072a7111ea5ebcfb30d/spec/aldous/respondable/headable/head_action_spec.rb | spec/aldous/respondable/headable/head_action_spec.rb | RSpec.describe Aldous::Respondable::Headable::HeadAction do
subject(:respondable) {described_class.new(controller, status)}
let(:controller) {double 'controller'}
let(:status) {'hello'}
before do
allow(controller).to receive(:head).with(status)
end
describe "#execute" do
it "calls head on controller with status" do
expect(controller).to receive(:head).with(status)
respondable.execute
end
end
end
| ruby | MIT | 0eb0a18b511345ad5fea3072a7111ea5ebcfb30d | 2026-01-04T17:54:58.048556Z | false |
envato-archive/aldous | https://github.com/envato-archive/aldous/blob/0eb0a18b511345ad5fea3072a7111ea5ebcfb30d/spec/aldous/respondable/send_data/send_data_action_spec.rb | spec/aldous/respondable/send_data/send_data_action_spec.rb | RSpec.describe Aldous::Respondable::SendData::SendDataAction do
subject(:respondable) {described_class.new(data, options, controller, result)}
let(:data) { 'hello' }
let(:options) {'world'}
let(:controller) {double 'controller', render: nil}
let(:result) {"blah"}
describe "#execute" do
it "calls render on controller with the relevant options" do
expect(controller).to receive(:send_data).with(data, options)
respondable.execute
end
end
end
| ruby | MIT | 0eb0a18b511345ad5fea3072a7111ea5ebcfb30d | 2026-01-04T17:54:58.048556Z | false |
envato-archive/aldous | https://github.com/envato-archive/aldous/blob/0eb0a18b511345ad5fea3072a7111ea5ebcfb30d/spec/aldous/respondable/renderable/render_action_spec.rb | spec/aldous/respondable/renderable/render_action_spec.rb | RSpec.describe Aldous::Respondable::Renderable::RenderAction do
subject(:respondable) {described_class.new(template, status, controller, view_data)}
let(:status) {:foo}
let(:template) { {hello: 'world'} }
let(:controller) {double 'controller', render: nil, flash: flash }
let(:view_data) {"blah"}
let(:response_status) {'world'}
let(:flash) { double("flash", now: flash_now) }
let(:flash_now) { double("flash_now") }
let(:flash_object) { instance_double Aldous::Respondable::Shared::Flash, set_error: nil }
describe "#execute" do
before do
allow(Aldous::Respondable::Shared::Flash).to receive(:new){ flash_object }
end
it "calls render on controller with the relevant options" do
expect(controller).to receive(:render).with(template.merge(status: status))
respondable.execute
end
it "tries to set flash" do
expect(Aldous::Respondable::Shared::Flash).to receive(:new).with(view_data, flash_now)
respondable.execute
end
it "calls set_error on flash object" do
expect(flash_object).to receive(:set_error)
respondable.execute
end
end
end
| ruby | MIT | 0eb0a18b511345ad5fea3072a7111ea5ebcfb30d | 2026-01-04T17:54:58.048556Z | false |
envato-archive/aldous | https://github.com/envato-archive/aldous/blob/0eb0a18b511345ad5fea3072a7111ea5ebcfb30d/spec/aldous/respondable/shared/flash_spec.rb | spec/aldous/respondable/shared/flash_spec.rb | RSpec.describe Aldous::Respondable::Shared::Flash do
let(:flash) {described_class.new(result, flash_container)}
let(:controller) {double 'controller', flash: flash_container}
let(:result) {double 'result', errors: errors}
let(:errors) {['1', '2']}
let(:flash_container) {double 'flash container', now: flash_now}
let(:flash_now) { {} }
describe "#set_error" do
context "when errors exist" do
let(:flash_container) { {} }
it "sets the error on the flash container" do
flash.set_error
expect(flash_container[:error]).to eq '1'
end
end
context "when errors don't exist" do
let(:errors) {[]}
let(:flash_container) { {} }
it "doesn't set the error on the flash container" do
flash.set_error
expect(flash_container[:error]).to eq nil
end
end
end
end
| ruby | MIT | 0eb0a18b511345ad5fea3072a7111ea5ebcfb30d | 2026-01-04T17:54:58.048556Z | false |
envato-archive/aldous | https://github.com/envato-archive/aldous/blob/0eb0a18b511345ad5fea3072a7111ea5ebcfb30d/examples/basic_todo/app/controller_actions/base_action.rb | examples/basic_todo/app/controller_actions/base_action.rb | class BaseAction < ::Aldous::ControllerAction
def default_view_data
{
current_user: current_user,
current_ability: current_ability,
}
end
def preconditions
[Shared::EnsureUserNotDisabledPrecondition]
end
def default_error_handler(error)
Defaults::ServerErrorView
end
def current_user
@current_user ||= FindCurrentUserService.perform(session).user
end
def current_ability
@current_ability ||= Ability.new(current_user)
end
end
| ruby | MIT | 0eb0a18b511345ad5fea3072a7111ea5ebcfb30d | 2026-01-04T17:54:58.048556Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.