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
midnightmonster/activerecord-summarize
https://github.com/midnightmonster/activerecord-summarize/blob/7371f06ce47b2bc6966a5b8297aa95aaee2c59de/lib/activerecord/summarize.rb
lib/activerecord/summarize.rb
# frozen_string_literal: true require_relative "summarize/version" require_relative "summarize/calculation_implementation" require_relative "../chainable_result" module ActiveRecord::Summarize class Unsummarizable < StandardError; end class Summarize attr_reader :current_result_row, :base_groups, :base_association, :pure, :noop, :from_where alias_method :pure?, :pure alias_method :noop?, :noop # noop: true # causes `summarize` simply to yield the original relation and a trivial, # synchronous `with` proc. It is meant as a convenient way to test/prove # the correctness of `summarize` and to compare performance of the single # combined query vs the original individual queries. # N.b., if `relation` already has a grouping applied, there is no direct # ActiveRecord translation for what `summarize` does, so noop: true is # impossible and raises an exception. # pure: true # lets `summarize` know that you're not mutating state within the block, # so it doesn't need to go spelunking in the block binding for # ChainableResults. See `if !pure?` section below. # N.b., if `relation` already has a grouping applied, pure: true is # implied and pure: false throws an exception, as the impure behavior # would be non-obvious and of doubtful value. def initialize(relation, pure: nil, noop: false) @relation = relation @noop = noop @base_groups, @base_association = relation.group_values.dup.then do |group_fields| # Based upon a bit from ActiveRecord::Calculations.execute_grouped_calculation, # if the base relation is grouped only by a belongs_to association, group by # the association's foreign key. if group_fields.size == 1 && group_fields.first.respond_to?(:to_sym) association = relation.klass._reflect_on_association(group_fields.first) # Like ActiveRecord's group(:association).count behavior, this only works with belongs_to associations next [Array(association.foreign_key), association] if association&.belongs_to? end [group_fields, nil] end has_base_groups = base_groups.any? raise Unsummarizable, "`summarize` must be pure when called on a grouped relation" if pure == false && has_base_groups raise ArgumentError, "`summarize(noop: true)` is impossible on a grouped relation" if noop && has_base_groups @pure = has_base_groups || !!pure @calculations = [] end def process(&block) # For noop, just yield the original relation and a transparent `with_resolved` proc. return yield(@relation, ChainableResult::SYNC_WITH_RESOLVED) if noop? # Within the block, the relation and its future clones intercept calls to # `count` and `sum`, registering them and returning a ChainableResult via # summarize.add_calculation. future_block_result = ChainableResult.wrap(yield( @relation.unscope(:group).tap do |r| r.instance_variable_set(:@summarize, self) class << r include InstanceMethods end end, ChainableResult::WITH_RESOLVED )) ChainableResult.with_cache(!pure?) do # `resolve` builds the single query that answers all collected calculations, # executes it, and aggregates the results by the values of `base_groups`. # In the common case of no `base_groups`, the resolve returns: # `{[]=>[*final_value_for_each_calculation]}` result = resolve.transform_values! do |row| # Each row (in the common case, only one) is used to resolve any # ChainableResults returned by the block. These may be a one-to-one mapping, # or the block return may have combined some results via `with`, chained # additional methods on results, etc.. @current_result_row = row future_block_result.value end.then do |result| # Now unpack/fix-up the result keys to match shape of Relation.count or Relation.group(*cols).count return values if base_groups.empty? # Change ungrouped result from `{[]=>v}` to `v`, like Relation.count result.values.first elsif base_association # Change grouped-by-one-belongs_to-association result from `{[id1]=>v1,[id2]=>v2,...}` to # `{<AssociatedModel id:id1>=>v1,<AssociatedModel id:id2>=>v2,...}` like Relation.group(:association).count # Loosely based on a bit from ActiveRecord::Calculations.execute_grouped_calculation, # retrieve the records for the group association and replace the keys of our final result. key_class = base_association.klass.base_class key_records = key_class .where(key_class.primary_key => result.keys.flatten) .index_by(&:id) result.transform_keys! { |k| key_records[k[0]] } elsif base_groups.size == 1 # Change grouped-by-one-column result from `{[k1]=>v1,[k2]=>v2,...}` to `{k1=>v1,k2=>v2,...}`, like Relation.group(:column).count result.transform_keys! { |k| k[0] } else # Multiple-column base grouping (though perhaps relatively rare) requires no change. result end end if !pure? # Check block scope's local vars and block's self's instance vars for # any ChainableResult, and replace it with its resolved value. # # Also check the values of any of those vars that are Hashes, since IME # it's not rare to assign counts to hashes, and it is rare to have giant # hashes that would be particularly wasteful to traverse. Do not do the # same for Arrays, since IME pushing counts to arrays is rare, and large # arrays, e.g., of many eagerly-fetched ActiveRecord objects, are not # rare in controllers. # # Preconditions: # - @current_result_row is still set to the single result row # - we are within a ChainableResult.with_cache(true) block block_binding = block.binding block_self = block_binding.receiver block_binding.local_variables.each do |k| v = block_binding.local_variable_get(k) next block_binding.local_variable_set(k, v.value) if v.is_a?(ChainableResult) lightly_touch_impure_hash(v) if v.is_a?(Hash) end block_self.instance_variables.each do |k| v = block_self.instance_variable_get(k) next block_self.instance_variable_set(k, v.value) if v.is_a?(ChainableResult) lightly_touch_impure_hash(v) if v.is_a?(Hash) end end @current_result_row = nil result end end def add_calculation(operation, relation, column_name) merge_from_where!(relation) calculation = CalculationImplementation.new(operation, relation, column_name) index = @calculations.size @calculations << calculation ChainableResult.wrap(calculation) { current_result_row[index] } end def resolve ######################### # Build & execute query # ######################### groups = all_groups # MariaDB, SQLite, and Postgres all support `GROUP BY 1, 2, 3`-style syntax, # where the numbers are 1-indexed references to SELECT values. grouped_query = groups.any? ? from_where.group(*1..groups.size) : from_where data = grouped_query.pluck(*groups, *value_selects) # .pluck(:just_one_column) returns an array of values instead of an array # of arrays, which breaks the aggregation and assignment below. data = data.map { |d| [d] } if (groups.size + value_selects.size) == 1 ############################## # Build aggregation reducers # ############################## # groups includes all base groups and all sub-groups group_idx = groups.each_with_index.to_h # Inverts the groups list: `[:foo, :bar]` becomes `{:foo => 0, :bar => 1}` starting_values, reducers = @calculations.each_with_index.map do |f, i| value_column = groups.size + i # each calculation shares any base groups that exist and may have sub-groups, which won't be shared by others group_columns = f.relation.group_values.map { |k| group_idx[k] } case group_columns.size when 0 then [ f.initial, ->(memo, row) { f.reducer(memo, row[value_column]) } ] when 1 then [ {}, ->(memo, row) { key = row[group_columns[0]] prev_val = memo[key] || f.initial next_val = f.reducer(prev_val, row[value_column]) memo[key] = next_val unless next_val == prev_val memo } ] else [ {}, ->(memo, row) { key = group_columns.map { |i| row[i] } prev_val = memo[key] || f.initial next_val = f.reducer(prev_val, row[value_column]) memo[key] = next_val unless next_val == prev_val memo } ] end end.transpose # For an array of pairs, `transpose` is the reverse of `zip` cols = (0...reducers.size) base_group_columns = (0...base_groups.size) data .group_by { |row| row[base_group_columns] } .tap { |h| h[[]] = [] if h.empty? && base_groups.empty? } .transform_values! do |rows| values = starting_values.map(&:dup) # map(&:dup) since some are hashes and we don't want to mutate starting_values rows.each do |row| cols.each do |i| values[i] = reducers[i].call(values[i], row) end end values end end private def compatible_base @compatible_base ||= @relation.except(:select, :group) end def merge_from_where!(other) other_from_where = other.except(:select, :group) incompatible_values = compatible_base.send(:structurally_incompatible_values_for, other_from_where) unless incompatible_values.empty? raise Unsummarizable, "Within a `summarize` block, each calculation must be structurally compatible. Incompatible values: #{incompatible_values}" end # Logical OR the criteria of all calculations. Most often this is equivalent # to `compatible_base`, since usually one is a total or grouped count without # additional `where` criteria, but that needn't necessarily be so. @from_where = if @from_where.nil? other_from_where else @from_where.or(other_from_where) end end def all_groups # keep all base groups, even if they did something silly like group by # the same key twice, but otherwise don't repeat any groups groups = base_groups.dup groups_set = Set.new(groups) @calculations.map { |f| f.relation.group_values }.flatten.each do |k| next if groups_set.include? k groups_set << k groups << k end groups end def value_selects @calculations.each_with_index.map do |f, i| f.select_column_arel_node(@relation) .as("_v#{i}") # In Postgres with certain Rails versions, alias is needed to disambiguate result column names for type information end end def lightly_touch_impure_hash(h) h.each do |k, v| h[k] = v.value if v.is_a? ChainableResult end end end module RelationMethods def summarize(**opts, &block) raise Unsummarizable, "Cannot summarize within a summarize block" if @summarize ActiveRecord::Summarize::Summarize.new(self, **opts).process(&block) end end module InstanceMethods private def perform_calculation(operation, column_name) case operation = operation.to_s.downcase when "count", "sum" column_name = :id if [nil, "*", :all].include? column_name # only applies to count raise Unsummarizable, "DISTINCT in SQL is not reliably correct with summarize" if column_name.is_a?(String) && /\bdistinct\b/i === column_name @summarize.add_calculation(operation, self, aggregate_column(column_name)) when "average" ChainableResult::WITH_RESOLVED[ perform_calculation("sum", column_name), perform_calculation("count", column_name) ] do |sum, count| if sum.is_a? Hash sum.to_h { |key, s| [key, s.to_d / count[key]] } else next nil if count == 0 sum.to_d / count end end when "minimum", "maximum" @summarize.add_calculation(operation, self, aggregate_column(column_name)) else super end end end end class ActiveRecord::Base class << self def summarize(**opts, &block) ActiveRecord::Summarize::Summarize.new(all, **opts).process(&block) end end end class ActiveRecord::Relation include ActiveRecord::Summarize::RelationMethods end
ruby
MIT
7371f06ce47b2bc6966a5b8297aa95aaee2c59de
2026-01-04T17:49:56.082596Z
false
midnightmonster/activerecord-summarize
https://github.com/midnightmonster/activerecord-summarize/blob/7371f06ce47b2bc6966a5b8297aa95aaee2c59de/lib/activerecord/summarize/version.rb
lib/activerecord/summarize/version.rb
# frozen_string_literal: true module ActiveRecord module Summarize VERSION = "0.5.1" end end
ruby
MIT
7371f06ce47b2bc6966a5b8297aa95aaee2c59de
2026-01-04T17:49:56.082596Z
false
midnightmonster/activerecord-summarize
https://github.com/midnightmonster/activerecord-summarize/blob/7371f06ce47b2bc6966a5b8297aa95aaee2c59de/lib/activerecord/summarize/calculation_implementation.rb
lib/activerecord/summarize/calculation_implementation.rb
module ActiveRecord::Summarize::CalculationImplementation def self.new(operation, relation, column_name) case operation when "sum" then Sum when "count" then Count when "minimum" then Minimum when "maximum" then Maximum else raise "Unknown calculation #{operation}" end.new(relation, column_name) end class Base attr_reader :relation, :column def initialize(relation, column) @relation = relation @column = column end def select_column_arel_node(base_relation) where = relation.where_clause - base_relation.where_clause for_select = column for_select = Arel::Nodes::Case.new(where.ast).when(true, for_select).else(unmatch_arel_node) unless where.empty? function_arel_node_class.new([for_select]).tap { |f| f.distinct = relation.distinct_value } end def function_arel_node_class # Arel::Node class representing the SQL function raise "`#{self.class}` must implement `function_arel_node_class`" end def unmatch_arel_node # In case of `where` filters, this is the does-not-count value for when # filters don't match, so far always 0 or nil (becomes NULL) raise "`#{self.class}` must implement `unmatch_arel_node`" end def initial # Initial value for reducing potentially many split-into-groups rows to # a single value, so far always 0 or nil. raise "`#{self.class}` must implement `initial`" end def reducer(memo, v) # Reducer method for reducing potentially many split-into-groups rows to # a single value. Method should return a value the same type as memo # and/or v. A reducer is necessary at all because .group in columns # _other than_ this one results in fragmenting this result into several # rows. raise "`#{self.class}` must implement `reducer`" end end class Sum < Base def unmatch_arel_node 0 # Adding zero to a sum does nothing end def function_arel_node_class Arel::Nodes::Sum end def initial 0 end def reducer(memo, v) memo + (v || 0) end end class Count < Base def unmatch_arel_node nil # In SQL, null is no value and is not counted end def function_arel_node_class Arel::Nodes::Count end def initial 0 end def reducer(memo, v) memo + (v || 0) end end class Minimum < Base def unmatch_arel_node nil # In SQL, null is no value and is not considered for min() end def function_arel_node_class Arel::Nodes::Min end def initial nil end def reducer(memo, v) return memo if v.nil? return v if memo.nil? (v < memo) ? v : memo end end class Maximum < Base def unmatch_arel_node nil # In SQL, null is no value and is not considered for max() end def function_arel_node_class Arel::Nodes::Max end def initial nil end def reducer(memo, v) return memo if v.nil? return v if memo.nil? (v > memo) ? v : memo end end end
ruby
MIT
7371f06ce47b2bc6966a5b8297aa95aaee2c59de
2026-01-04T17:49:56.082596Z
false
tlossen/remodel
https://github.com/tlossen/remodel/blob/82a0222e02ab07cc1a6fbb99f749300dc4868315/test/test_has_many.rb
test/test_has_many.rb
require 'helper' require 'json' class TestHasMany < Test::Unit::TestCase class Puzzle < Remodel::Entity has_many :pieces, :class => 'TestHasMany::Piece' property :topic end class Piece < Remodel::Entity property :color end context "association" do should "exist" do assert Puzzle.create(context).respond_to?(:pieces) end should "return an empty list by default" do assert_equal [], Puzzle.create(context).pieces end should "return any existing children" do puzzle = Puzzle.create(context) red_piece = Piece.create(context, :color => 'red') blue_piece = Piece.create(context, :color => 'blue') redis.hset(context.key, "#{puzzle.key}_pieces", "#{red_piece.key} #{blue_piece.key}") assert_equal 2, puzzle.pieces.size assert_equal Piece, puzzle.pieces[0].class assert_equal 'red', puzzle.pieces[0].color end should "not return any child multiple times" do puzzle = Puzzle.create(context) red_piece = Piece.create(context, :color => 'red') redis.hset(context.key, "#{puzzle.key}_pieces", "#{red_piece.key} #{red_piece.key}") assert_equal 1, puzzle.pieces.size assert_equal Piece, puzzle.pieces[0].class assert_equal 'red', puzzle.pieces[0].color end context "create" do should "have a create method" do assert Puzzle.create(context).pieces.respond_to?(:create) end should "work without attributes" do puzzle = Puzzle.create(context) piece = puzzle.pieces.create assert piece.is_a?(Piece) end should "create and store a new child" do puzzle = Puzzle.create(context) puzzle.pieces.create :color => 'green' assert_equal 1, puzzle.pieces.size puzzle.reload assert_equal 1, puzzle.pieces.size assert_equal Piece, puzzle.pieces[0].class assert_equal 'green', puzzle.pieces[0].color end end context "add" do should "add the given entity to the association" do puzzle = Puzzle.create(context) piece = Piece.create(context, :color => 'white') puzzle.pieces.add piece assert_equal 1, puzzle.pieces.size puzzle.reload assert_equal 1, puzzle.pieces.size assert_equal Piece, puzzle.pieces[0].class assert_equal 'white', puzzle.pieces[0].color end end context "find" do setup do @puzzle = Puzzle.create(context) 5.times { @puzzle.pieces.create :color => 'blue' } end should "find the element with the given id" do piece = @puzzle.pieces[2] assert_equal piece, @puzzle.pieces.find(piece.id) end should "raise an exception if no element with the given id exists" do assert_raises(Remodel::EntityNotFound) { @puzzle.pieces.find(-1) } end end end context "reload" do should "reset has_many associations" do puzzle = Puzzle.create(context) piece = puzzle.pieces.create :color => 'black' redis.hdel(context.key, "#{puzzle.key}_pieces") puzzle.reload assert_equal [], puzzle.pieces end end end
ruby
MIT
82a0222e02ab07cc1a6fbb99f749300dc4868315
2026-01-04T17:49:55.198629Z
false
tlossen/remodel
https://github.com/tlossen/remodel/blob/82a0222e02ab07cc1a6fbb99f749300dc4868315/test/test_shortnames.rb
test/test_shortnames.rb
require 'helper' class TestShortnames < Test::Unit::TestCase class Foo < Remodel::Entity; end class Bar < Remodel::Entity property :test, :short => 'z' has_one :foo, :short => 'y', :class => Foo has_many :foos, :short => 'x', :class => Foo end context "property shortnames" do setup do @bar = Bar.create(context, :test => 42) end should "be used when storing properties" do serialized = redis.hget(context.key, @bar.key) assert !serialized.match(/test/) assert serialized.match(/z/) end should "work in roundtrip" do @bar.reload assert_equal 42, @bar.test end should "not be used in as_json" do assert !@bar.as_json.has_key?(:z) assert @bar.as_json.has_key?(:test) end should "not be used in inspect" do assert !@bar.inspect.match(/z/) assert @bar.inspect.match(/test/) end end context "has_one shortnames" do setup do @bar = Bar.create(context, :test => 42) @bar.foo = Foo.create(context) end should "be used when storing" do assert_not_nil redis.hget(context.key, "#{@bar.key}_y") end should "work in roundtrip" do @bar.reload assert_not_nil @bar.foo end end context "has_many shortnames" do setup do @bar = Bar.create(context, :test => 42) @bar.foos.create @bar.foos.create end should "be used when storing" do assert_not_nil redis.hget(context.key, "#{@bar.key}_x") end should "work in roundtrip" do @bar.reload assert_equal 2, @bar.foos.size end end end
ruby
MIT
82a0222e02ab07cc1a6fbb99f749300dc4868315
2026-01-04T17:49:55.198629Z
false
tlossen/remodel
https://github.com/tlossen/remodel/blob/82a0222e02ab07cc1a6fbb99f749300dc4868315/test/test_caching_context.rb
test/test_caching_context.rb
# encoding: UTF-8 require 'helper' class Remodel::CachingContext attr_accessor :cache class << self public :new end end class TestCachingContext < Test::Unit::TestCase context "CachingContext" do setup do @cache = Remodel::CachingContext.new(context) end context 'hget' do should "fetch and cache value" do context.expects(:hget).with('x').returns('33') assert_equal '33', @cache.hget('x') assert_equal '33', @cache.cache['x'] end should "return cached value" do @cache.cache['x'] = '42' context.expects(:hget).never assert_equal '42', @cache.hget('x') end should "return cached nil" do @cache.cache['x'] = nil context.expects(:hget).never assert_nil @cache.hget('x') end end context 'hmget' do should "fetch and cache values" do context.expects(:hmget).with('x', 'y', 'z').returns %w[4 5 6] assert_equal %w[4 5 6], @cache.hmget('x', 'y', 'z') assert_equal %w[4 5 6], @cache.cache.values_at('x', 'y', 'z') end should 'only fetch uncached values' do @cache.cache['y'] = '5' context.expects(:hmget).with('x', 'z').returns %w[4 6] assert_equal %w[4 5 6], @cache.hmget('x', 'y', 'z') assert_equal %w[4 5 6], @cache.cache.values_at('x', 'y', 'z') end should 'not fetch cached nil values' do @cache.cache['y'] = nil context.expects(:hmget).with('x', 'z').returns %w[4 6] assert_equal ['4', nil, '6'], @cache.hmget('x', 'y', 'z') assert_equal ['4', nil, '6'], @cache.cache.values_at('x', 'y', 'z') end should 'not call redis if all values are cached' do @cache.cache['x'] = '4' @cache.cache['y'] = '5' @cache.cache['z'] = '6' context.expects(:hmget).never assert_equal %w[4 5 6], @cache.hmget('x', 'y', 'z') end end context 'hset' do should 'store value in redis' do context.expects(:hset).with('x', '21') @cache.hset('x', 21) end should 'cache value as string' do context.expects(:hset).with('x', '21') @cache.hset('x', 21) assert_equal '21', @cache.cache['x'] end should 'cache nil' do context.expects(:hset).with('x', nil) @cache.hset('x', nil) assert_nil @cache.cache['x'] assert @cache.cache.has_key?('x') end end context 'hincrby' do should 'increment value in redis' do context.expects(:hincrby).with('i', 1).returns(3) assert_equal 3, @cache.hincrby('i', 1) end should 'cache result as string' do context.expects(:hincrby).with('i', 1).returns(3) @cache.hincrby('i', 1) assert_equal '3', @cache.cache['i'] end end context 'hdel' do should 'delete field in redis' do context.expects(:hdel).with('x') @cache.hdel('x') end should 'cache nil for field' do context.expects(:hdel).with('x') @cache.hdel('x') assert_nil @cache.cache['x'] assert @cache.cache.has_key?('x') end end context 'batched' do should "ensure batched blocks are not nested" do assert_raise(Remodel::InvalidUse) do @cache.batched do @cache.batched do end end end end should "collect hset calls into one hmset" do context.expects(:hset).never context.expects(:hmset).with('a', '3', 'b', '2') #might break in ruby 1.8 @cache.batched do @cache.hset('a', 1) @cache.hset('b', 2) @cache.hset('a', 3) end end should "collect hdel calls into one hmdel" do context.expects(:hdel).never context.expects(:hmdel).with('a', 'b') @cache.batched do @cache.hdel('a') @cache.hdel('b') @cache.hdel('a') end end should "handle multiple hset and hdel to the same field" do context.expects(:hset).never context.expects(:hdel).never context.expects(:hmset).with('a', '3') context.expects(:hmdel).with() @cache.batched do @cache.hset('a', 1) @cache.hdel('a') @cache.hset('a', 3) end end should "handle hincrby" do context.expects(:hset).never context.expects(:hmset).with('i', '2') @cache.batched do @cache.hdel('i') @cache.hincrby('i', 1) @cache.hincrby('i', 1) end end end end end
ruby
MIT
82a0222e02ab07cc1a6fbb99f749300dc4868315
2026-01-04T17:49:55.198629Z
false
tlossen/remodel
https://github.com/tlossen/remodel/blob/82a0222e02ab07cc1a6fbb99f749300dc4868315/test/test_entity_delete.rb
test/test_entity_delete.rb
require 'helper' class TestEntityDelete < Test::Unit::TestCase class Group < Remodel::Entity has_many :members, :class => 'TestEntityDelete::Person' has_one :room, :class => 'TestEntityDelete::Room' property :name end class Person < Remodel::Entity property :name end class Room < Remodel::Entity property :name end context "delete" do setup do redis.flushdb @group = Group.create(context, :name => 'ruby user group') @tim = @group.members.create(:name => 'Tim') @group.members.create(:name => 'Ben') @room = Room.create(context, :name => 'some office') @group.room = @room @group.reload end should "ensure that the entity is persistent" do assert_raise(Remodel::EntityNotSaved) { Group.new(context).delete } end should "delete the given entity" do @group.delete assert_nil redis.hget(context.key, @group.key) end should "delete any associations in redis" do @group.delete assert_nil redis.hget(context.key, "#{@group.key}_members") assert_nil redis.hget(context.key, "#{@group.key}_room") end context "has_one" do should "be nil if deleted" do @room.delete assert_nil @group.room end end context "has_many" do should "be skipped if deleted" do @tim.delete assert_equal 1, @group.members.count end end end end
ruby
MIT
82a0222e02ab07cc1a6fbb99f749300dc4868315
2026-01-04T17:49:55.198629Z
false
tlossen/remodel
https://github.com/tlossen/remodel/blob/82a0222e02ab07cc1a6fbb99f749300dc4868315/test/test_remodel.rb
test/test_remodel.rb
require 'helper' class TestRemodel < Test::Unit::TestCase context "create_context" do should "create a context" do context = Remodel.create_context('foo') assert_equal Remodel::Context, context.class assert_equal 'foo', context.key end should "create a caching context, if specified" do context = Remodel.create_context('foo', :caching => true) assert_equal Remodel::CachingContext, context.class assert_equal 'foo', context.key end end end
ruby
MIT
82a0222e02ab07cc1a6fbb99f749300dc4868315
2026-01-04T17:49:55.198629Z
false
tlossen/remodel
https://github.com/tlossen/remodel/blob/82a0222e02ab07cc1a6fbb99f749300dc4868315/test/test_has_one.rb
test/test_has_one.rb
require 'helper' class TestHasOne < Test::Unit::TestCase class Piece < Remodel::Entity has_one :puzzle, :class => 'TestHasOne::Puzzle' property :color end class Puzzle < Remodel::Entity property :topic end context "association getter" do should "exist" do assert Piece.create(context).respond_to?(:puzzle) end should "return nil by default" do assert_nil Piece.create(context).puzzle end should "return the associated entity" do puzzle = Puzzle.create(context, :topic => 'animals') piece = Piece.create(context) redis.hset(context.key, "#{piece.key}_puzzle", puzzle.key) assert_equal 'animals', piece.puzzle.topic end end context "association setter" do should "exist" do assert Piece.create(context).respond_to?(:'puzzle=') end should "store the key of the associated entity" do puzzle = Puzzle.create(context) piece = Piece.create(context) piece.puzzle = puzzle assert_equal puzzle.key, redis.hget(context.key, "#{piece.key}_puzzle") end should "be settable to nil" do piece = Piece.create(context) piece.puzzle = nil assert_nil piece.puzzle end should "remove the key if set to nil" do piece = Piece.create(context) piece.puzzle = Puzzle.create(context) piece.puzzle = nil assert_nil redis.hget(piece.context, "#{piece.key}_puzzle") end end context "reload" do should "reset has_one associations" do piece = Piece.create(context, :color => 'black') piece.puzzle = Puzzle.create(context) redis.hdel(context.key, "#{piece.key}_puzzle") piece.reload assert_nil piece.puzzle end end end
ruby
MIT
82a0222e02ab07cc1a6fbb99f749300dc4868315
2026-01-04T17:49:55.198629Z
false
tlossen/remodel
https://github.com/tlossen/remodel/blob/82a0222e02ab07cc1a6fbb99f749300dc4868315/test/test_entity_defaults.rb
test/test_entity_defaults.rb
require 'helper' class TestEntityDefaults < Test::Unit::TestCase class Bar < Remodel::Entity property :simple, :default => 123 property :array, :default => [1] property :hash, :default => { :foo => 1 } end context "[default values]" do should "be returned for missing properties" do bar = Bar.new(context) assert_equal 123, bar.simple end should "be returned for properties that are nil" do bar = Bar.new(context, :simple => 'cool') bar.simple = nil assert_equal 123, bar.simple end should "not be returned for given properties" do bar = Bar.new(context, :simple => 'cool') assert_equal 'cool', bar.simple end should "not be stored" do bar = Bar.create(context) assert !(/123/ =~ redis.hget(context, bar.key)) end should "be returned by as_json" do bar = Bar.new(context) assert_equal 123, bar.as_json[:simple] end end context "[collections]" do setup do @bar, @baz = Bar.new(context), Bar.new(context) end should "not share arrays" do @bar.array[0] += 1 assert_equal [1], @baz.array end should "not share hashes" do @bar.hash[:foo] = 42 assert_equal 1, @baz.hash[:foo] end end end
ruby
MIT
82a0222e02ab07cc1a6fbb99f749300dc4868315
2026-01-04T17:49:55.198629Z
false
tlossen/remodel
https://github.com/tlossen/remodel/blob/82a0222e02ab07cc1a6fbb99f749300dc4868315/test/test_mappers.rb
test/test_mappers.rb
require 'helper' class Item < Remodel::Entity property :boolean, :class => Boolean property :string, :class => String property :integer, :class => Integer property :float, :class => Float property :array, :class => Array property :hash, :class => Hash property :time, :class => Time property :date, :class => Date end class TestMappers < Test::Unit::TestCase context "create" do setup do @item = Item.create(context, :time => Time.at(1234567890), :date => Date.parse("1972-06-16")) end should "store unmapped values" do assert_equal Time, @item.instance_eval { @attributes[:time].class } assert_equal Date, @item.instance_eval { @attributes[:date].class } end should "not change mapped values" do assert_equal Time.at(1234567890), @item.time assert_equal Date.parse("1972-06-16"), @item.date end should "not change mapped values after reload" do @item.reload assert_equal Time.at(1234567890), @item.time assert_equal Date.parse("1972-06-16"), @item.date end should "serialize mapped values correctly" do json = redis.hget(context.key, @item.key) assert_match /1234567890/, json assert_match /"1972-06-16"/, json end should "handle nil values" do item = Item.create(context) assert_nil item.boolean assert_nil item.string assert_nil item.integer assert_nil item.float assert_nil item.array assert_nil item.hash assert_nil item.time assert_nil item.date end should "reject invalid types" do assert_raise(Remodel::InvalidType) { Item.create(context, :boolean => 'hello') } assert_raise(Remodel::InvalidType) { Item.create(context, :string => true) } assert_raise(Remodel::InvalidType) { Item.create(context, :integer => 33.5) } assert_raise(Remodel::InvalidType) { Item.create(context, :float => 5) } assert_raise(Remodel::InvalidType) { Item.create(context, :array => {}) } assert_raise(Remodel::InvalidType) { Item.create(context, :hash => []) } assert_raise(Remodel::InvalidType) { Item.create(context, :time => Date.new) } assert_raise(Remodel::InvalidType) { Item.create(context, :date => Time.now) } end end end
ruby
MIT
82a0222e02ab07cc1a6fbb99f749300dc4868315
2026-01-04T17:49:55.198629Z
false
tlossen/remodel
https://github.com/tlossen/remodel/blob/82a0222e02ab07cc1a6fbb99f749300dc4868315/test/test_entity.rb
test/test_entity.rb
require 'helper' class Foo < Remodel::Entity property :x property :y end class Bar < Remodel::Entity property :d, :default => 123 end class TestEntity < Test::Unit::TestCase context "new" do should "set properties" do foo = Foo.new(context, :x => 1, :y => 2) assert_equal 1, foo.x assert_equal 2, foo.y end should "ignore undefined properties" do foo = Foo.new(context, :z => 3) assert foo.instance_eval { !@attributes.key? :z } end should "not set the key" do foo = Foo.new(context, :x => 23) assert_equal nil, foo.key end should "not set the id" do foo = Foo.new(context, :x => 23) assert_equal nil, foo.id end end context "create" do setup do redis.flushdb end should "work without attributes" do foo = Foo.create(context) assert foo.is_a?(Foo) end should "give the entity a key based on the class name" do assert_equal 'f1', Foo.create(context).key assert_equal 'b1', Bar.create(context).key assert_equal 'b2', Bar.create(context).key end should "give the entity an id which is unique per entity class" do assert_equal 1, Foo.create(context).id assert_equal 1, Bar.create(context).id assert_equal 2, Bar.create(context).id end should "store the entity under its key" do foo = Foo.create(context, :x => 'hello', :y => false) assert redis.hexists(context.key, foo.key) end should "store all properties" do foo = Foo.create(context, :x => 'hello', :y => false) foo.reload assert_equal 'hello', foo.x assert_equal false, foo.y end should "not store the key as a property" do foo = Foo.create(context, :x => 'hello', :y => false) assert !(/f1/ =~ redis.hget(context.key, foo.key)) end end context "save" do setup do redis.flushdb end should "give the entity a key, if necessary" do foo = Foo.new(context).save assert foo.key end should "store the entity under its key" do foo = Foo.new(context, :x => 'hello', :y => false) foo.save assert redis.hexists(context.key, foo.key) end should "store all properties" do foo = Foo.new(context, :x => 'hello', :y => false) foo.save foo.reload assert_equal 'hello', foo.x assert_equal false, foo.y end should "not store nil values" do foo = Foo.new(context, :x => nil, :y => false) foo.save foo.reload assert_nil foo.x assert_equal '{"y":false}', redis.hget(context.key, foo.key) end end context "reload" do setup do @foo = Foo.create(context, :x => 'hello', :y => true) end should "reload all properties" do redis.hset(context.key, @foo.key, %q({"x":23,"y":"adios"})) @foo.reload assert_equal 23, @foo.x assert_equal 'adios', @foo.y end should "keep the key" do key = @foo.key @foo.reload assert_equal key, @foo.key end should "stay the same object" do id = @foo.object_id @foo.reload assert_equal id, @foo.object_id end should "raise EntityNotFound if the entity does not exist any more" do redis.hdel(context.key, @foo.key) assert_raise(Remodel::EntityNotFound) { @foo.reload } end should "raise EntityNotSaved if the entity was never saved" do assert_raise(Remodel::EntityNotSaved) { Foo.new(context).reload } end end context "update" do setup do redis.flushdb @foo = Foo.create(context, :x => 'Tim', :y => true) end should "set the given properties" do @foo.update(:x => 12, :y => 'Jan') assert_equal 12, @foo.x assert_equal 'Jan', @foo.y end should "save the entity" do @foo.update(:x => 12, :y => 'Jan') @foo.reload assert_equal 12, @foo.x assert_equal 'Jan', @foo.y end end context "to_json" do should "serialize to json" do foo = Foo.new(context, :x => 42, :y => true) assert_match /"x":42/, foo.to_json assert_match /"y":true/, foo.to_json end end context "as_json" do should "serialize into a hash" do foo = Foo.create(context, :x => 42, :y => true) expected = { :id => foo.id, :x => 42, :y => true } assert_equal expected, foo.as_json end end context "#set_key_prefix" do should "use the given key prefix" do class Custom < Remodel::Entity; set_key_prefix 'my'; end assert_match /^my\d+$/, Custom.create(context).key end should "ensure that the prefix is letters only" do assert_raise(Remodel::InvalidKeyPrefix) do class InvalidPrefix < Remodel::Entity; set_key_prefix '666'; end end end should "ensure that the class is a direct subclass of entity" do assert_raise(Remodel::InvalidUse) do class InvalidSetPrefix < Foo; set_key_prefix 'x'; end end end end context "#find" do setup do redis.flushdb @foo = Foo.create(context, :x => 'hello', :y => 123) Foo.create(context, :x => 'hallo', :y => 124) end should "find and load an entity by key" do foo = Foo.find(@foo.context, @foo.key) assert_equal foo.x, @foo.x assert_equal foo.y, @foo.y end should "find and load an entity by id" do foo = Foo.find(@foo.context, @foo.id) assert_equal foo.x, @foo.x assert_equal foo.y, @foo.y end should "reject a key which does not exist" do assert_raise(Remodel::EntityNotFound) { Foo.find(context, 'x66') } end should "reject an id which does not exist" do assert_raise(Remodel::EntityNotFound) { Foo.find(context, 66) } end end context "properties" do should "have property x" do foo = Foo.new(context) foo.x = 23 assert_equal 23, foo.x foo.x += 10 assert_equal 33, foo.x end should "not have property z" do foo = Foo.new(context) assert_raise(NoMethodError) { foo.z } assert_raise(NoMethodError) { foo.z = 42 } end context "types" do should "work with nil" do foo = Foo.create(context, :x => nil) assert_equal nil, foo.reload.x end should "work with booleans" do foo = Foo.create(context, :x => false) assert_equal false, foo.reload.x end should "work with integers" do foo = Foo.create(context, :x => -42) assert_equal -42, foo.reload.x end should "work with floats" do foo = Foo.create(context, :x => 3.141) assert_equal 3.141, foo.reload.x end should "work with strings" do foo = Foo.create(context, :x => 'hello') assert_equal 'hello', foo.reload.x end should "work with lists" do foo = Foo.create(context, :x => [1, 2, 3]) assert_equal [1, 2, 3], foo.reload.x end should "work with hashes" do hash = { 'a' => 17, 'b' => 'test' } foo = Foo.create(context, :x => hash) assert_equal hash, foo.reload.x end end end context "#restore" do should "restore an entity from json" do before = Foo.create(context, :x => 42, :y => true) after = Foo.restore(context, before.key, before.to_json) assert_equal before.key, after.key assert_equal before.x, after.x assert_equal before.y, after.y end end end
ruby
MIT
82a0222e02ab07cc1a6fbb99f749300dc4868315
2026-01-04T17:49:55.198629Z
false
tlossen/remodel
https://github.com/tlossen/remodel/blob/82a0222e02ab07cc1a6fbb99f749300dc4868315/test/helper.rb
test/helper.rb
require 'rubygems' require 'test/unit' require 'shoulda' require 'mocha' require File.dirname(__FILE__) + '/../lib/remodel.rb' class Test::Unit::TestCase def redis Remodel.redis end def context @context ||= Remodel.create_context('test') end end
ruby
MIT
82a0222e02ab07cc1a6fbb99f749300dc4868315
2026-01-04T17:49:55.198629Z
false
tlossen/remodel
https://github.com/tlossen/remodel/blob/82a0222e02ab07cc1a6fbb99f749300dc4868315/test/test_monkeypatches.rb
test/test_monkeypatches.rb
require 'helper' class TestMonkeypatches < Test::Unit::TestCase context "Boolean" do should "be the superclass of both true and false" do assert true.is_a?(Boolean) assert false.is_a?(Boolean) end end context "Class[]" do should "return given Class objects" do assert_equal String, Class[String] end should "return the Class object for a given String" do assert_equal String, Class['String'] end should "return the Class object for a given Symbol" do assert_equal String, Class[:String] end should "work for nested classes" do assert_equal Remodel::Entity, Class['Remodel::Entity'] end end end
ruby
MIT
82a0222e02ab07cc1a6fbb99f749300dc4868315
2026-01-04T17:49:55.198629Z
false
tlossen/remodel
https://github.com/tlossen/remodel/blob/82a0222e02ab07cc1a6fbb99f749300dc4868315/test/test_inheritance.rb
test/test_inheritance.rb
require 'helper' class TestInheritance < Test::Unit::TestCase class Foo < Remodel::Entity property :test end class Bar < Remodel::Entity property :test end class Person < Remodel::Entity property :name, :short => 'n' has_one :foo, :class => Foo has_many :foos, :class => Foo end class Admin < Person property :password, :short => 'p' has_one :bar, :class => Bar has_many :bars, :class => Bar end context "a subclass of another entity" do setup do @admin = Admin.create(context, :name => 'peter', :password => 'secret') end should "inherit properties" do @admin.reload assert_equal 'peter', @admin.name assert_equal 'secret', @admin.password end should "inherit has_one associations" do @admin.foo = Foo.create(context, :test => 'foo') @admin.bar = Bar.create(context, :test => 'bar') @admin.reload assert_equal 'foo', @admin.foo.test assert_equal 'bar', @admin.bar.test end should "inherit has_many associations" do @admin.foos.create(:test => 'foo') @admin.bars.create(:test => 'bar') @admin.reload assert_equal 'foo', @admin.foos[0].test assert_equal 'bar', @admin.bars[0].test end should "be usable as superclass" do person = Person.find(context, @admin.key) assert_equal 'peter', person.name assert_raise(NoMethodError) { person.password } end should "use property shortnames in redis" do json = redis.hget(context.key, @admin.key) assert_match /"n":/, json assert_match /"p":/, json end should "use the same prefix as the superclass" do assert_equal 'p', Admin.key_prefix end end end
ruby
MIT
82a0222e02ab07cc1a6fbb99f749300dc4868315
2026-01-04T17:49:55.198629Z
false
tlossen/remodel
https://github.com/tlossen/remodel/blob/82a0222e02ab07cc1a6fbb99f749300dc4868315/example/book.rb
example/book.rb
require File.dirname(__FILE__) + "/../lib/remodel" class Book < Remodel::Entity has_many :chapters, :class => 'Chapter' property :title, :short => 't', :class => 'String' property :year, :class => 'Integer' property :author, :class => 'String', :default => '(anonymous)' end class Chapter < Remodel::Entity property :title, :class => String end
ruby
MIT
82a0222e02ab07cc1a6fbb99f749300dc4868315
2026-01-04T17:49:55.198629Z
false
tlossen/remodel
https://github.com/tlossen/remodel/blob/82a0222e02ab07cc1a6fbb99f749300dc4868315/lib/remodel.rb
lib/remodel.rb
require 'rubygems' require 'redis' require 'date' require 'set' # If available, use the superfast YAJL lib to parse JSON. begin require 'yajl/json_gem' rescue LoadError require 'json' end # Define `Boolean` -- the missing superclass of `true` and `false`. module Boolean; end true.extend(Boolean) false.extend(Boolean) # Find the `Class` object for a given class name, which can be # a `String` or a `Symbol` (or a `Class`). def Class.[](clazz) return clazz if clazz.nil? or clazz.is_a?(Class) clazz.to_s.split('::').inject(Kernel) { |mod, name| mod.const_get(name) } end require File.join(File.dirname(__FILE__), 'remodel', 'mapper') require File.join(File.dirname(__FILE__), 'remodel', 'has_many') require File.join(File.dirname(__FILE__), 'remodel', 'entity') require File.join(File.dirname(__FILE__), 'remodel', 'context') require File.join(File.dirname(__FILE__), 'remodel', 'caching_context') module Remodel # Custom errors class Error < ::StandardError; end class EntityNotFound < Error; end class EntityNotSaved < Error; end class InvalidKeyPrefix < Error; end class InvalidType < Error; end class MissingContext < Error; end class InvalidUse < Error; end # By default, the redis server is expected to listen at `localhost:6379`. # Otherwise you will have to set `Remodel.redis` to a suitably initialized # redis client. def self.redis @redis ||= Redis.new end def self.redis=(redis) @redis = redis end def self.create_context(key, options = {}) context = Context.send(:new, key) context = CachingContext.send(:new, context) if options[:caching] context end # Returns the mapper defined for a given class, or the identity mapper. def self.mapper_for(clazz) mapper_by_class[Class[clazz]] end # Define some mappers for common types. def self.mapper_by_class @mapper_by_class ||= Hash.new(Mapper.new).merge( Boolean => Mapper.new(Boolean), String => Mapper.new(String), Integer => Mapper.new(Integer), Float => Mapper.new(Float), Array => Mapper.new(Array), Hash => Mapper.new(Hash), Date => Mapper.new(Date, :to_s, :parse), Time => Mapper.new(Time, :to_i, :at) ) end end
ruby
MIT
82a0222e02ab07cc1a6fbb99f749300dc4868315
2026-01-04T17:49:55.198629Z
false
tlossen/remodel
https://github.com/tlossen/remodel/blob/82a0222e02ab07cc1a6fbb99f749300dc4868315/lib/remodel/caching_context.rb
lib/remodel/caching_context.rb
# encoding: UTF-8 module Remodel class CachingContext # use Remodel.create_context instead class << self private :new end def initialize(context) @context = context @cache = {} end def key @context.key end def batched raise InvalidUse, "cannot nest batched blocks" if @dirty begin @dirty = Set.new yield ensure to_delete = @dirty.select { |field| @cache[field].nil? } to_update = (@dirty - to_delete).to_a @context.hmset(*to_update.zip(@cache.values_at(*to_update)).flatten) @context.hmdel(*to_delete) @dirty = nil end end def hget(field) @cache[field] = @context.hget(field) unless @cache.has_key?(field) @cache[field] end def hmget(*fields) load(fields - @cache.keys) @cache.values_at(*fields) end def hset(field, value) value = value.to_s if value @cache[field] = value @dirty ? @dirty.add(field) : @context.hset(field, value) end def hincrby(field, value) new_value = @dirty ? hget(field).to_i + value : @context.hincrby(field, value) @cache[field] = new_value.to_s @dirty.add(field) if @dirty new_value end def hdel(field) @cache[field] = nil @dirty ? @dirty.add(field) : @context.hdel(field) end def inspect "\#<#{self.class.name}(#{@context.inspect})>" end private def load(fields) return if fields.empty? fields.zip(@context.hmget(*fields)).each do |field, value| @cache[field] = value end end end end
ruby
MIT
82a0222e02ab07cc1a6fbb99f749300dc4868315
2026-01-04T17:49:55.198629Z
false
tlossen/remodel
https://github.com/tlossen/remodel/blob/82a0222e02ab07cc1a6fbb99f749300dc4868315/lib/remodel/entity.rb
lib/remodel/entity.rb
module Remodel # The superclass of all persistent remodel entities. class Entity attr_accessor :context, :key def initialize(context, attributes = {}, key = nil) @context = context @attributes = {} @key = key attributes.each do |name, value| send("#{name}=", value) if respond_to? "#{name}=" end end def id key && key.match(/\d+/)[0].to_i end def save @key = next_key unless @key @context.hset(@key, to_json) self end def update(properties) properties.each { |name, value| send("#{name}=", value) } save end def reload raise EntityNotSaved unless @key attributes = self.class.parse(self.class.fetch(@context, @key)) initialize(@context, attributes, @key) self.class.associations.each do |name| var = "@#{name}".to_sym remove_instance_variable(var) if instance_variable_defined? var end self end def delete raise EntityNotSaved unless @key @context.hdel(@key) self.class.associations.each do |name| @context.hdel("#{@key}_#{name}") end end def as_json { :id => id }.merge(attributes) end def to_json JSON.generate(self.class.pack(@attributes)) end def inspect properties = attributes.map { |name, value| "#{name}: #{value.inspect}" }.join(', ') "\#<#{self.class.name}(#{context.key}, #{id}) #{properties}>" end def self.create(context, attributes = {}) new(context, attributes).save end def self.find(context, key) key = "#{key_prefix}#{key}" if key.kind_of? Integer restore(context, key, fetch(context, key)) end def self.restore(context, key, json) new(context, parse(json), key) end protected # --- DSL for subclasses --- def self.set_key_prefix(prefix) raise(InvalidKeyPrefix, prefix) unless prefix =~ /^[a-z]+$/ raise(InvalidUse, "can only set key prefix for direct subclasses of entity") unless superclass == Entity @key_prefix = prefix end def self.property(name, options = {}) name = name.to_sym _mapper[name] = Remodel.mapper_for(options[:class]) define_shortname(name, options[:short]) default_value = options[:default] define_method(name) { @attributes[name].nil? ? self.class.copy_of(default_value) : @attributes[name] } define_method("#{name}=") { |value| @attributes[name] = value } end def self.has_many(name, options) _associations.push(name) var = "@#{name}".to_sym shortname = options[:short] || name define_method(name) do if instance_variable_defined? var instance_variable_get(var) else clazz = Class[options[:class]] instance_variable_set(var, HasMany.new(self, clazz, "#{key}_#{shortname}")) end end end def self.has_one(name, options) _associations.push(name) var = "@#{name}".to_sym shortname = options[:short] || name define_method(name) do if instance_variable_defined? var instance_variable_get(var) else clazz = Class[options[:class]] value_key = self.context.hget("#{key}_#{shortname}") value = value_key && clazz.find(self.context, value_key) rescue nil instance_variable_set(var, value) end end define_method("#{name}=") do |value| if value instance_variable_set(var, value) self.context.hset("#{key}_#{shortname}", value.key) else remove_instance_variable(var) if instance_variable_defined? var self.context.hdel("#{key}_#{shortname}") end end end private # --- Helper methods --- def attributes result = {} self.class.mapper.keys.each do |name| result[name] = send(name) end result end def self.fetch(context, key) context.hget(key) || raise(EntityNotFound, "no #{name} with key #{key} in context #{context}") end # Each entity has its own sequence to generate unique ids. def next_key id = @context.hincrby("#{self.class.key_prefix}", 1) "#{self.class.key_prefix}#{id}" end def self.parse(json) unpack(JSON.parse(json)) end def self.pack(attributes) result = {} attributes.each do |name, value| short = shortname[name] || name value = mapper[name].pack(value) result[short] = value unless value.nil? end result end def self.unpack(attributes) result = {} attributes.each do |short, value| short = short.to_sym name = fullname[short] || short result[name] = mapper[name].unpack(value) if mapper[name] end result end def self.copy_of(value) value.is_a?(Array) || value.is_a?(Hash) ? value.dup : value end def self.define_shortname(name, short) return unless short short = short.to_sym _shortname[name] = short _fullname[short] = name end # class instance variables: # lazy init + recursive lookup in superclasses def self.key_prefix superclass == Entity ? _key_prefix : superclass.key_prefix end # Default key prefix is the first letter of the class name, in lowercase. def self._key_prefix @key_prefix ||= name.split('::').last[0,1].downcase end def self.mapper superclass == Entity ? _mapper : superclass.mapper.merge(_mapper) end def self._mapper @mapper ||= {} end def self.shortname superclass == Entity ? _shortname : superclass.shortname.merge(_shortname) end def self._shortname @shortname ||= {} end def self.fullname superclass == Entity ? _fullname : superclass.fullname.merge(_fullname) end def self._fullname @fullname ||= {} end def self.associations superclass == Entity ? _associations : superclass.associations + _associations end def self._associations @associations ||= [] end end end
ruby
MIT
82a0222e02ab07cc1a6fbb99f749300dc4868315
2026-01-04T17:49:55.198629Z
false
tlossen/remodel
https://github.com/tlossen/remodel/blob/82a0222e02ab07cc1a6fbb99f749300dc4868315/lib/remodel/has_many.rb
lib/remodel/has_many.rb
module Remodel # Represents the many-end of a many-to-one or many-to-many association. class HasMany < Array def initialize(this, clazz, key) super _fetch(clazz, this.context, key) @this, @clazz, @key = this, clazz, key end def create(attributes = {}) add(@clazz.create(@this.context, attributes)) end def find(id) detect { |x| x.id == id } || raise(EntityNotFound, "no element with id #{id}") end def add(entity) self << entity _store entity end def remove(entity) delete_if { |x| x.key == entity.key } _store entity end private def _store @this.context.hset(@key, self.map(&:key).join(' ')) end def _fetch(clazz, context, key) keys = (context.hget(key) || '').split.uniq values = keys.empty? ? [] : context.hmget(*keys) keys.zip(values).map do |key, json| clazz.restore(context, key, json) if json end.compact end end end
ruby
MIT
82a0222e02ab07cc1a6fbb99f749300dc4868315
2026-01-04T17:49:55.198629Z
false
tlossen/remodel
https://github.com/tlossen/remodel/blob/82a0222e02ab07cc1a6fbb99f749300dc4868315/lib/remodel/context.rb
lib/remodel/context.rb
module Remodel class Context # use Remodel.create_context instead class << self private :new end attr_reader :key def initialize(key) @key = key end def hget(field) Remodel.redis.hget(@key, field) end def hmget(*fields) Remodel.redis.hmget(@key, *fields) end def hset(field, value) Remodel.redis.hset(@key, field, value) end def hmset(*fields_and_values) return if fields_and_values.empty? Remodel.redis.hmset(@key, *fields_and_values) end def hincrby(field, value) Remodel.redis.hincrby(@key, field, value) end def hdel(field) Remodel.redis.hdel(@key, field) end def hmdel(*fields) return if fields.empty? Remodel.redis.pipelined do fields.each { |field| Remodel.redis.hdel(@key, field) } end end def inspect "\#<#{self.class.name}(#{@key})>" end end end
ruby
MIT
82a0222e02ab07cc1a6fbb99f749300dc4868315
2026-01-04T17:49:55.198629Z
false
tlossen/remodel
https://github.com/tlossen/remodel/blob/82a0222e02ab07cc1a6fbb99f749300dc4868315/lib/remodel/mapper.rb
lib/remodel/mapper.rb
module Remodel # A mapper converts a given value into a native JSON value &mdash; # *nil*, *true*, *false*, *Number*, *String*, *Hash*, *Array* &mdash; # via `pack`, and back again via `unpack`. # # Without any arguments, `Mapper.new` returns the identity mapper, which # maps every value to itself. If `clazz` is set, the mapper rejects any # value which is not of the given type. class Mapper def initialize(clazz = nil, pack_method = nil, unpack_method = nil) @clazz = clazz @pack_method = pack_method @unpack_method = unpack_method end def pack(value) return nil if value.nil? raise(InvalidType, "#{value.inspect} is not a #{@clazz}") if @clazz && !value.is_a?(@clazz) @pack_method ? value.send(@pack_method) : value end def unpack(value) return nil if value.nil? @unpack_method ? @clazz.send(@unpack_method, value) : value end end end
ruby
MIT
82a0222e02ab07cc1a6fbb99f749300dc4868315
2026-01-04T17:49:55.198629Z
false
Sandthorn/sandthorn
https://github.com/Sandthorn/sandthorn/blob/68b37655c857dd588e950cdcde99056060beaf56/spec/aggregate_delta_spec.rb
spec/aggregate_delta_spec.rb
require 'spec_helper' class PersonTest include Sandthorn::AggregateRoot attr_reader :name attr_reader :age attr_reader :relationship_status attr_reader :my_array attr_reader :my_hash def initialize name, age, relationship_status @name = name @age = age @relationship_status = relationship_status @my_array = [] @my_hash = {} end def change_name new_name @name = new_name record_event end def change_relationship new_relationship @relationship_status = new_relationship record_event end def add_to_array element @my_array << element record_event end def add_to_hash name,value @my_hash[name] = value record_event end end describe 'Property Delta Event Sourcing' do let(:person) { PersonTest.new "Lasse",40,:married} it 'should be able to set name' do person.change_name "Klabbarparen" expect(person.name).to eq("Klabbarparen") end it 'should be able to build from events' do person.change_name "Klabbarparen" builded = PersonTest.aggregate_build person.aggregate_events expect(builded.name).to eq(person.name) expect(builded.aggregate_id).to eq(person.aggregate_id) end it 'should not have any events when built up' do person.change_name "Mattias" builded = PersonTest.aggregate_build person.aggregate_events expect(builded.aggregate_events).to be_empty end it 'should detect change on array' do person.add_to_array "Foo" person.add_to_array "bar" builded = PersonTest.aggregate_build person.aggregate_events expect(builded.my_array).to include "Foo" expect(builded.my_array).to include "bar" end it 'should detect change on hash' do person.add_to_hash :foo, "bar" person.add_to_hash :bar, "foo" builded = PersonTest.aggregate_build person.aggregate_events expect(builded.my_hash[:foo]).to eq("bar") expect(builded.my_hash[:bar]).to eq("foo") person.add_to_hash :foo, "BAR" builded2 = PersonTest.aggregate_build person.aggregate_events expect(builded2.my_hash[:foo]).to eq("BAR") end end
ruby
MIT
68b37655c857dd588e950cdcde99056060beaf56
2026-01-04T17:49:58.000055Z
false
Sandthorn/sandthorn
https://github.com/Sandthorn/sandthorn/blob/68b37655c857dd588e950cdcde99056060beaf56/spec/event_stores_spec.rb
spec/event_stores_spec.rb
require 'spec_helper' module Sandthorn describe EventStores do let(:stores) { EventStores.new } before do class AnAggregate include Sandthorn::AggregateRoot end end describe "#initialize" do context "when given a single event_store" do it "sets it as the default event store" do store = double(get_events: true) allow(store).to receive(:get_events) stores = EventStores.new(store) expect(stores.default_store).to eq(store) end end context "when given number of stores" do it "adds them all" do stores = { default: double, other: double } repo = EventStores.new(stores) expect(repo.by_name(:default)).to eq(stores[:default]) expect(repo.by_name(:other)).to eq(stores[:other]) end end end describe "enumerable" do let(:store) { double } let(:other_store) { double } it "should respond to each" do expect(stores).to respond_to(:each) end it "should yield each store" do stores.add_many( foo: store, bar: other_store ) expect { |block| stores.each(&block) }.to yield_successive_args(store, other_store) end end describe "#default_store=" do it "sets the default" do store = double stores = EventStores.new stores.default_store = store expect(stores.default_store).to eq(store) end end describe "#by_name" do context "when the store exists" do it "returns the store" do store = double stores.add(:foo, store) expect(stores.by_name(:foo)).to eq(store) end end context "when the store does not exist" do it "returns the default store" do store = double stores.default_store = store expect(stores.by_name(:unknown)).to eq(store) end end end describe "#add" do it "adds the store under the given name" do store = double stores.add(:foo, store) expect(stores[:foo]).to eq(store) end end describe "#map_types" do context "map two events stores" do class AnAggregate1 include Sandthorn::AggregateRoot end class AnAggregate2 include Sandthorn::AggregateRoot end before do store = double stores.add(:foo, store) stores.add(:bar, store) stores.map_types(foo: [AnAggregate1], bar: [AnAggregate2]) end it "should map event_store foo to AnAggregate1" do expect(AnAggregate1.event_store).to eq(:foo) end it "should map event_store bar to AnAggregate2" do expect(AnAggregate2.event_store).to eq(:bar) end end end end end
ruby
MIT
68b37655c857dd588e950cdcde99056060beaf56
2026-01-04T17:49:58.000055Z
false
Sandthorn/sandthorn
https://github.com/Sandthorn/sandthorn/blob/68b37655c857dd588e950cdcde99056060beaf56/spec/complex_aggregate_spec.rb
spec/complex_aggregate_spec.rb
require 'spec_helper' require 'date' class Hello attr_reader :foo_bar attr_accessor :change_me def initialize foo_bar @foo_bar = foo_bar end def set_foo_bar value @foo_bar = value end end class IAmComplex include Sandthorn::AggregateRoot attr_reader :a_date attr_reader :hello def set_hello! hello set_hello_event hello end def set_foo_bar_on_hello value @hello.set_foo_bar value commit end def initialize date @a_date = date end private def set_hello_event hello @hello = hello commit end end describe 'when using complex types in events' do before(:each) do aggr = IAmComplex.new Date.new 2012,01,20 aggr.set_hello! Hello.new "foo" @events = aggr.aggregate_events end it 'should be able to build from events' do aggr = IAmComplex.aggregate_build @events expect(aggr.a_date).to be_a(Date) expect(aggr.hello).to be_a(Hello) end it 'should detect hello changing' do aggr = IAmComplex.aggregate_build @events hello = aggr.hello hello.change_me = ["Fantastisk"] aggr.set_hello! hello hello.change_me << "Otroligt" aggr.set_hello! hello builded = IAmComplex.aggregate_build aggr.aggregate_events expect(builded.hello.change_me).to include "Fantastisk" expect(builded.hello.change_me).to include "Otroligt" end it 'should detect foo_bar chaning in hello' do aggr = IAmComplex.aggregate_build @events aggr.set_foo_bar_on_hello "morgan" builded = IAmComplex.aggregate_build aggr.aggregate_events expect(builded.hello.foo_bar).to eq("morgan") end end
ruby
MIT
68b37655c857dd588e950cdcde99056060beaf56
2026-01-04T17:49:58.000055Z
false
Sandthorn/sandthorn
https://github.com/Sandthorn/sandthorn/blob/68b37655c857dd588e950cdcde99056060beaf56/spec/stateless_events_spec.rb
spec/stateless_events_spec.rb
require 'spec_helper' module Sandthorn class StatelessEventsSpec include AggregateRoot stateless_events :one_event, :some_other_event attr_reader :name def initialize name @name = name end end describe "::stateless_events" do let(:args) do {first: "first", other: [1,2,3]} end context "interface" do it "should expose stateless_events methods" do expect(StatelessEventsSpec).to respond_to(:one_event) end end context "when adding a stateless event to an existing aggregate" do let(:subject) do StatelessEventsSpec.new("name").save end before do StatelessEventsSpec.one_event(subject.aggregate_id, args) end let(:last_event) do Sandthorn.find(subject.aggregate_id, StatelessEventsSpec).last end let(:reloaded_subject) do StatelessEventsSpec.find subject.aggregate_id end it "should add one_event last on the aggregate" do expect(last_event[:event_name]).to eq("one_event") end it "should add aggregate_id to events" do expect(last_event[:aggregate_id]).to eq(subject.aggregate_id) end it "should have stateless data in deltas in event" do expect(last_event[:event_data]).to eq({:first => {:old_value => nil, :new_value => "first"}, :other => {:old_value => nil, :new_value => [1, 2, 3]}}) end it "should have same name attribute after reload" do expect(subject.name).to eq(reloaded_subject.name) end end context "when adding stateless_events to none existing aggregate" do before do StatelessEventsSpec.one_event(aggregate_id, args) end let(:aggregate_id) {"none_existing_aggregate_id"} let(:events) do Sandthorn.find aggregate_id, StatelessEventsSpec end it "should store the stateless event as the first event" do expect(events.length).to be 1 end it "should have correct aggregate_id in event" do expect(events.first[:aggregate_id]).to eq(aggregate_id) end it "should have event name one_event" do expect(events.first[:event_name]).to eq("one_event") end end context "overriding properties with stateless data" do let(:subject) do StatelessEventsSpec.new("name").save end let(:reloaded_subject) do StatelessEventsSpec.find subject.aggregate_id end let(:args) do {name: "ghost"} end before do StatelessEventsSpec.one_event(subject.aggregate_id, args) end it "should override the name via the stateless event" do expect(subject.name).not_to eq(reloaded_subject.name) end end end end
ruby
MIT
68b37655c857dd588e950cdcde99056060beaf56
2026-01-04T17:49:58.000055Z
false
Sandthorn/sandthorn
https://github.com/Sandthorn/sandthorn/blob/68b37655c857dd588e950cdcde99056060beaf56/spec/constructor_events_spec.rb
spec/constructor_events_spec.rb
require 'spec_helper' module Sandthorn class ConstructorEventsSpec include AggregateRoot constructor_events :created_event attr_reader :name def self.create name created_event(name) { @name = name } end end describe "::constructor_events" do let(:subject) do ConstructorEventsSpec.create("name").save end context "interface" do it "should not expose constructor_events methods" do expect(subject).not_to respond_to(:created_event) end it "should create the constructor event on the class" do expect(ConstructorEventsSpec.private_methods).to include(:created_event) end end end describe "::create" do let(:aggregate_id) do a = ConstructorEventsSpec.create("create_name") a.save a.aggregate_id end it "should create an ConstructorEventsSpec aggregate" do expect(ConstructorEventsSpec.find(aggregate_id)).to be_a ConstructorEventsSpec end it "should set instance variable in aggregate" do expect(ConstructorEventsSpec.find(aggregate_id).name).to eq("create_name") end it "should have created an created_event" do expect(Sandthorn.find(aggregate_id, ConstructorEventsSpec).first[:event_name]).to eq("created_event") end it "should have set the attribute_delta name" do expect(Sandthorn.find(aggregate_id, ConstructorEventsSpec).first[:event_data]).to have_key(:name) expect(Sandthorn.find(aggregate_id, ConstructorEventsSpec).first[:event_data][:name][:new_value]).to eq("create_name") end end end
ruby
MIT
68b37655c857dd588e950cdcde99056060beaf56
2026-01-04T17:49:58.000055Z
false
Sandthorn/sandthorn
https://github.com/Sandthorn/sandthorn/blob/68b37655c857dd588e950cdcde99056060beaf56/spec/tracing_spec.rb
spec/tracing_spec.rb
require 'spec_helper' require 'sandthorn/event_inspector' class UsualSuspect include Sandthorn::AggregateRoot def initialize full_name @full_name = full_name @charges = [] end def charge_suspect_of_crime! crime_name suspect_was_charged crime_name end private def suspect_was_charged crime_name @charges << crime_name record_event end end class Simple include Sandthorn::AggregateRoot end module Go def go @foo = "bar" record_event end end describe "using a traced change" do context "when extending an instance with aggregate_root" do it "should record tracing if specified" do simple = Simple.new simple.extend Sandthorn::EventInspector simple.extend Go simple.aggregate_trace "123" do |traced| traced.go end expect(simple.events_with_trace_info.last[:event_metadata]).to eq("123") end end context "when not tracing" do it "should not have any trace event info at all on new" do suspect = UsualSuspect.new "Ronny" event = suspect.aggregate_events.first expect(event[:event_metadata]).to be_nil end it "should not have any trace event info at all on regular event" do suspect = UsualSuspect.new "Ronny" event = suspect.aggregate_events.first expect(event[:event_metadata]).to be_nil end end context "when changing aggregate in a traced context" do let(:suspect) {UsualSuspect.new("Conny").extend Sandthorn::EventInspector} it "should record modififier in the event" do suspect.aggregate_trace "Ture Sventon" do |s| s.charge_suspect_of_crime! "Theft" end event = suspect.events_with_trace_info.last expect(event[:event_metadata]).to eq("Ture Sventon") end it "should record optional other tracing information" do trace_info = {ip: "127.0.0.1", client: "Mozilla"} suspect.aggregate_trace trace_info do |s| s.charge_suspect_of_crime! "Murder" end event = suspect.events_with_trace_info.last expect(event[:event_metadata]).to eq(trace_info) end end context "when initializing a new aggregate in a traced context" do it "should record modifier in the new event" do UsualSuspect.aggregate_trace "Ture Sventon" do suspect = UsualSuspect.new("Sonny").extend Sandthorn::EventInspector event = suspect.events_with_trace_info.first expect(event[:event_metadata]).to eq("Ture Sventon") end end it "should record tracing for all events in the trace block" do trace_info = {gender: :unknown, occupation: :master} UsualSuspect.aggregate_trace trace_info do suspect = UsualSuspect.new("Sonny").extend Sandthorn::EventInspector suspect.charge_suspect_of_crime! "Hit and run" event = suspect.events_with_trace_info.last expect(event[:event_metadata]).to eq(trace_info) end end it "should record tracing for all events in the trace block" do trace_info = {user_aggregate_id: "foo-bar-x", gender: :unknown, occupation: :master} UsualSuspect.aggregate_trace trace_info do suspect = UsualSuspect.new("Conny").extend Sandthorn::EventInspector suspect.charge_suspect_of_crime! "Desception" event = suspect.events_with_trace_info.last expect(event[:event_metadata]).to eq(trace_info) end end end end
ruby
MIT
68b37655c857dd588e950cdcde99056060beaf56
2026-01-04T17:49:58.000055Z
false
Sandthorn/sandthorn
https://github.com/Sandthorn/sandthorn/blob/68b37655c857dd588e950cdcde99056060beaf56/spec/aggregate_events_spec.rb
spec/aggregate_events_spec.rb
require 'spec_helper' require 'sandthorn/event_inspector' module Sandthorn class EventsSpec include AggregateRoot events :name_changed, :some_other_event, :third_event attr_reader :name def change_name(name) if @name != name name_changed(name) { @name = name } end end def some_other one, two some_other_event one, two end def old_way_event event_params commit end end describe "::events" do let(:subject) do EventsSpec.new.extend EventInspector end it "should not expose events methods" do expect(subject).not_to respond_to(:name_changed) end it "should make the events methods private" do expect(subject.private_methods).to include(:name_changed) end describe ".change_name" do before do subject.change_name "new name" end it "should set the name instance variable" do expect(subject.name).to eq("new name") end it "should store the event params as methods args" do expect(subject.has_event?(:name_changed)).to be_truthy end it "should store the args to the event" do expect(subject.aggregate_events[1][:event_data][:name][:new_value]).to eq("new name") end it "should store the event_name" do expect(subject.aggregate_events[1][:event_name]).to eq("name_changed") end end describe ".some_other" do before do subject.some_other 1, 2 end it "should store the event" do expect(subject.has_event?(:some_other_event)).to be_truthy end end describe ".old_way_event" do before do subject.old_way_event "hej" end it "should store the event the old way" do expect(subject.has_event?(:old_way_event)).to be_truthy end end end end
ruby
MIT
68b37655c857dd588e950cdcde99056060beaf56
2026-01-04T17:49:58.000055Z
false
Sandthorn/sandthorn
https://github.com/Sandthorn/sandthorn/blob/68b37655c857dd588e950cdcde99056060beaf56/spec/snapshot_spec.rb
spec/snapshot_spec.rb
require 'spec_helper' module Sandthorn module Snapshot class KlassOne include Sandthorn::AggregateRoot snapshot true end class KlassTwo include Sandthorn::AggregateRoot end class KlassThree include Sandthorn::AggregateRoot end describe "::snapshot" do before do Sandthorn.configure do |c| c.snapshot_types = [KlassTwo] end end it "snapshot should be enabled on KlassOne and KlassTwo but not KlassThree" do expect(KlassOne.snapshot).to be_truthy expect(KlassTwo.snapshot).to be_truthy expect(KlassThree.snapshot).not_to be_truthy end end describe "find snapshot on snapshot enabled aggregate" do let(:klass) { KlassOne.new.save } it "should find on snapshot enabled Class" do copy = KlassOne.find klass.aggregate_id expect(copy.aggregate_version).to eql(klass.aggregate_version) end it "should get saved snapshot" do copy = Sandthorn.find_snapshot klass.aggregate_id expect(copy.aggregate_version).to eql(klass.aggregate_version) end end describe "save and find snapshot on snapshot disabled aggregate" do let(:klass) { KlassThree.new.save } it "should not find snapshot" do snapshot = Sandthorn.find_snapshot klass.aggregate_id expect(snapshot).to be_nil end it "should save and get saved snapshot" do Sandthorn.save_snapshot klass snapshot = Sandthorn.find_snapshot klass.aggregate_id expect(snapshot).not_to be_nil #Check by key on the snapshot_store hash expect(Sandthorn.snapshot_store.store.has_key?(klass.aggregate_id)).to be_truthy end end end end
ruby
MIT
68b37655c857dd588e950cdcde99056060beaf56
2026-01-04T17:49:58.000055Z
false
Sandthorn/sandthorn
https://github.com/Sandthorn/sandthorn/blob/68b37655c857dd588e950cdcde99056060beaf56/spec/default_attributes_spec.rb
spec/default_attributes_spec.rb
require 'spec_helper' # class DefaultAttributes # include Sandthorn::AggregateRoot # def initialize # end # end describe "when the initialize-method changes" do before do class DefaultAttributes include Sandthorn::AggregateRoot def initialize end end end #Make sure the DefaultAttributes class are reset on every test after do Object.send(:remove_const, :DefaultAttributes) end it "should not have an array attribute on first version of the DefaultAttributes class" do aggregate = DefaultAttributes.new expect(aggregate.respond_to?(:array)).to be_falsy end context "default_attributes" do def add_default_attributes DefaultAttributes.class_eval do attr_reader :array define_method :default_attributes, lambda { @array = [] } define_method :add_item, lambda { |item| @array << item commit } end end it "should have an set the array attribute to [] on new" do add_default_attributes aggregate = DefaultAttributes.new expect(aggregate.array).to eq([]) end it "should have set the array attribute to [] on rebuilt when attribute is intruduced after `new`" do aggregate = DefaultAttributes.new add_default_attributes rebuilt_aggregate = DefaultAttributes.aggregate_build(aggregate.aggregate_events) expect(rebuilt_aggregate.array).to eq([]) end it "should set the array attribute to ['banana'] on rebuilt" do add_default_attributes aggregate = DefaultAttributes.new aggregate.add_item 'banana' rebuilt_aggregate = DefaultAttributes.aggregate_build(aggregate.aggregate_events) expect(rebuilt_aggregate.array).to eq(['banana']) end end end
ruby
MIT
68b37655c857dd588e950cdcde99056060beaf56
2026-01-04T17:49:58.000055Z
false
Sandthorn/sandthorn
https://github.com/Sandthorn/sandthorn/blob/68b37655c857dd588e950cdcde99056060beaf56/spec/bounded_context_spec.rb
spec/bounded_context_spec.rb
require 'spec_helper' require 'sandthorn/bounded_context' module Sandthorn describe BoundedContext do it 'should respond to `aggregate_types`' do expect(BoundedContext).to respond_to(:aggregate_types) end end describe "::aggregate_types" do module TestModule include Sandthorn::BoundedContext class AnAggregate include Sandthorn::AggregateRoot end class NotAnAggregate end module Deep class DeepAggregate include Sandthorn::AggregateRoot end end end it "aggregate_types should include AnAggregate" do expect(TestModule.aggregate_types).to include(TestModule::AnAggregate) end it "aggregate_types should not include NotAnAggregate" do expect(TestModule.aggregate_types).not_to include(TestModule::NotAnAggregate) end it "aggregate_types should include DeepAnAggregate in a nested Module" do expect(TestModule.aggregate_types).to include(TestModule::Deep::DeepAggregate) end end end
ruby
MIT
68b37655c857dd588e950cdcde99056060beaf56
2026-01-04T17:49:58.000055Z
false
Sandthorn/sandthorn
https://github.com/Sandthorn/sandthorn/blob/68b37655c857dd588e950cdcde99056060beaf56/spec/initialize_signature_change_spec.rb
spec/initialize_signature_change_spec.rb
require 'spec_helper' class InitChange include Sandthorn::AggregateRoot attr_reader :foo def initialize foo: nil @foo = foo end end def change_init InitChange.class_eval do define_method :initialize, lambda { @foo = :foo } end end describe "when the initialize-method changes" do it "should be possible to replay anyway" do aggregate = InitChange.new foo: :bar events = aggregate.aggregate_events change_init with_change = InitChange.new expect(with_change.foo).to eq(:foo) replayed = InitChange.aggregate_build(events) expect(replayed.foo).to eq(:bar) end end
ruby
MIT
68b37655c857dd588e950cdcde99056060beaf56
2026-01-04T17:49:58.000055Z
false
Sandthorn/sandthorn
https://github.com/Sandthorn/sandthorn/blob/68b37655c857dd588e950cdcde99056060beaf56/spec/benchmark_spec.rb
spec/benchmark_spec.rb
require 'spec_helper' require 'benchmark' module Sandthorn module AggregateRoot class TestClass include Sandthorn::AggregateRoot attr_reader :name def initialize args = {} end def change_name value unless name == value @name = value commit end end end describe "benchmark", benchmark: true do let(:test_object) { o = TestClass.new().save o } n = 500 it "should new, change_name, save and find 500 aggregates" do Benchmark.bm do |x| x.report("new change save find") { for i in 1..n; s = TestClass.new().change_name("benchmark").save(); TestClass.find(s.id); end } end end it "should find 500 aggregates" do Benchmark.bm do |x| x.report("find") { for i in 1..n; TestClass.find(test_object.id); end } end end it "should commit 500 actions" do Benchmark.bm do |x| x.report("commit") { for i in 1..n; test_object.change_name "#{i}"; end } end end it "should commit and save 500 actions" do Benchmark.bm do |x| x.report("commit save") { for i in 1..n; test_object.change_name("#{i}").save; end } end end end end end
ruby
MIT
68b37655c857dd588e950cdcde99056060beaf56
2026-01-04T17:49:58.000055Z
false
Sandthorn/sandthorn
https://github.com/Sandthorn/sandthorn/blob/68b37655c857dd588e950cdcde99056060beaf56/spec/spec_helper.rb
spec/spec_helper.rb
# This file was generated by the `rspec --init` command. Conventionally, all # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. # Require this file using `require "spec_helper"` to ensure that it is only # loaded once. # # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration require 'coveralls' Coveralls.wear! require "ap" require "bundler" require "sandthorn_driver_sequel" require "support/custom_matchers" Bundler.require module Helpers def class_including(mod) Class.new.tap {|c| c.send :include, mod } end end RSpec.configure do |config| config.run_all_when_everything_filtered = true config.filter_run :focus config.filter_run_excluding benchmark: true # Run specs in random order to surface order dependencies. If you find an # order dependency and want to debug it, you can fix the order by providing # the seed, which is printed after each run. # --seed 1234 config.order = 'random' config.before(:all) { sqlite_store_setup } config.before(:each) { migrator = SandthornDriverSequel::Migration.new url: url migrator.send(:clear_for_test) } config.after(:all) do Sandthorn.event_stores.default_store.driver.instance_variable_get(:@db).disconnect end end def url "sqlite://spec/db/sequel_driver.sqlite3" end def sqlite_store_setup SandthornDriverSequel.migrate_db url: url Sandthorn.configure do |c| c.event_store = SandthornDriverSequel.driver_from_url(url: url) end end
ruby
MIT
68b37655c857dd588e950cdcde99056060beaf56
2026-01-04T17:49:58.000055Z
false
Sandthorn/sandthorn
https://github.com/Sandthorn/sandthorn/blob/68b37655c857dd588e950cdcde99056060beaf56/spec/aggregate_root_spec.rb
spec/aggregate_root_spec.rb
require 'spec_helper' module Sandthorn module AggregateRoot class DirtyClass include Sandthorn::AggregateRoot attr_reader :name, :age attr :age attr_writer :writer def initialize args = {} @name = args.fetch(:name, nil) @age = args.fetch(:age, nil) @writer = args.fetch(:writer, nil) end def change_name value unless name == value @name = value commit end end def change_age value unless age == value @age = value commit end end def change_writer value unless writer == value @writer = value commit end end def no_state_change_only_empty_event commit end end describe "::event_store" do let(:klass) { Class.new { include Sandthorn::AggregateRoot } } it "is available as a class method" do expect(klass).to respond_to(:event_store) end it "sets the event store as a class level variable and returns it" do klass.event_store(:other) expect(klass.event_store).to eq(:other) end end describe "::snapshot" do let(:klass) { Class.new { include Sandthorn::AggregateRoot } } it "is available as a class method" do expect(klass).to respond_to(:snapshot) end it "sets the snapshot to true and returns it" do klass.snapshot(true) expect(klass.snapshot).to eq(true) end end describe "when get all aggregates from DirtyClass" do before(:each) do @first = DirtyClass.new.save @middle = DirtyClass.new.save @last = DirtyClass.new.save end let(:subject) { DirtyClass.all.map{ |s| s.id} } let(:ids) { [@first.id, @middle.id, @last.id] } context "all" do it "should all the aggregates" do expect(subject.length).to eq(3) end it "should include correct aggregates" do expect(subject).to match_array(ids) end end end describe "when making a change on a aggregate" do let(:dirty_object) { o = DirtyClass.new o } context "new with args" do let(:subject) { DirtyClass.new(name: "Mogge", age: 35, writer: true) } it "should set the values" do expect(subject.name).to eq("Mogge") expect(subject.age).to eq(35) expect{subject.writer}.to raise_error NoMethodError end end context "when changing name (attr_reader)" do it "should get new_name" do dirty_object.change_name "new_name" expect(dirty_object.name).to eq("new_name") end it "should generate one event on new" do expect(dirty_object.aggregate_events.length).to eq(1) end it "should generate 2 events new and change_name" do dirty_object.change_name "new_name" expect(dirty_object.aggregate_events.length).to eq(2) end end context "when changing age (attr)" do it "should get new_age" do dirty_object.change_age "new_age" expect(dirty_object.age).to eq("new_age") end end context "when changing writer (attr_writer)" do it "should raise error" do expect{dirty_object.change_writer "new_writer"}.to raise_error NameError end end context "save" do it "should not have events on aggregate after save" do expect(dirty_object.save.aggregate_events.length).to eq(0) end it "should have aggregate_originating_version == 0 pre save" do expect(dirty_object.aggregate_originating_version).to eq(0) end it "should have aggregate_originating_version == 1 post save" do expect(dirty_object.save.aggregate_originating_version).to eq(1) end end context "find" do before(:each) { dirty_object.save } it "should find by id" do expect(DirtyClass.find(dirty_object.id).id).to eq(dirty_object.id) end it "should hold changed name" do dirty_object.change_name("morgan").save expect(DirtyClass.find(dirty_object.id).name).to eq("morgan") end it "should raise error if trying to find id that not exist" do expect{DirtyClass.find("666")}.to raise_error Sandthorn::Errors::AggregateNotFound end end end describe "event data" do let(:dirty_object) { o = DirtyClass.new :name => "old_value", :age => 35 o.save } let(:dirty_object_after_find) { DirtyClass.find dirty_object.id } context "after find" do it "should set the old_value on the event" do dirty_object_after_find.change_name "new_name" expect(dirty_object_after_find.aggregate_events.last[:event_data][:name][:old_value]).to eq("old_value") end end context "old_value should be set" do it "should set the old_value on the event" do dirty_object.change_name "new_name" expect(dirty_object.aggregate_events.last[:event_data][:name][:old_value]).to eq("old_value") end it "should not change aggregate_id" do dirty_object.change_name "new_name" expect(dirty_object.aggregate_events.last[:event_data]["attribute_name"]).not_to eq("aggregate_id") end it "should not change age attribute if age method is not runned" do dirty_object.change_name "new_name" dirty_object.aggregate_events.each do |event| expect(event[:event_data]["age"].nil?).to be_truthy end end it "should not change age attribute if age attribute is the same" do dirty_object.change_age 35 dirty_object.aggregate_events.each do |event| expect(event[:event_data]["age"].nil?).to be_truthy end end it "should set old_value and new_value on age change" do dirty_object.change_age 36 expect(dirty_object.aggregate_events.last[:event_data][:age][:old_value]).to eq(35) expect(dirty_object.aggregate_events.last[:event_data][:age][:new_value]).to eq(36) end end end context "events should be created event if no state change is made" do let(:dirty_object) do DirtyClass.new.save.tap do |o| o.no_state_change_only_empty_event end end it "should have the event no_state_change_only_empty_event" do expect(dirty_object.aggregate_events.first[:event_name]).to eq("no_state_change_only_empty_event") end it "should have event_data set to empty hash" do expect(dirty_object.aggregate_events.first[:event_data]).to eq({}) end end end end
ruby
MIT
68b37655c857dd588e950cdcde99056060beaf56
2026-01-04T17:49:58.000055Z
false
Sandthorn/sandthorn
https://github.com/Sandthorn/sandthorn/blob/68b37655c857dd588e950cdcde99056060beaf56/spec/support/custom_matchers.rb
spec/support/custom_matchers.rb
require 'rspec/expectations' RSpec::Matchers.define :have_aggregate_type do |expected| match do |actual| actual[:aggregate_type].to_s == expected.to_s end end
ruby
MIT
68b37655c857dd588e950cdcde99056060beaf56
2026-01-04T17:49:58.000055Z
false
Sandthorn/sandthorn
https://github.com/Sandthorn/sandthorn/blob/68b37655c857dd588e950cdcde99056060beaf56/lib/sandthorn.rb
lib/sandthorn.rb
require "sandthorn/version" require "sandthorn/errors" require "sandthorn/aggregate_root" require "sandthorn/event_stores" require "sandthorn/application_snapshot_store" require 'yaml' require 'securerandom' module Sandthorn class << self extend Forwardable def_delegators :configuration, :event_stores def_delegators :configuration, :snapshot_store def default_event_store event_stores.default_store end def default_event_store=(store) event_stores.default_store = store end def configure yield(configuration) if block_given? end def configuration @configuration ||= Configuration.new end def generate_aggregate_id SecureRandom.uuid end def save_events aggregate_events, aggregate_id, aggregate_type event_store_for(aggregate_type).save_events aggregate_events, aggregate_id, *aggregate_type end def all aggregate_type event_store_for(aggregate_type).all(aggregate_type) end def find aggregate_id, aggregate_type, after_aggregate_version = 0 event_store_for(aggregate_type).find(aggregate_id, aggregate_type, after_aggregate_version) end def save_snapshot aggregate raise Errors::SnapshotError, "Can't take snapshot on object with unsaved events" if aggregate.unsaved_events? snapshot_store.save aggregate.aggregate_id, aggregate end def find_snapshot aggregate_id return snapshot_store.find aggregate_id end def find_event_store(name) event_stores.by_name(name) end private def event_store_for(aggregate_type) event_store = event_stores.by_name(aggregate_type.event_store).tap do |store| yield(store) if block_given? end end def missing_key(key) raise ArgumentError, "missing keyword: #{key}" end class Configuration extend Forwardable def_delegators :default_store, :event_stores, :default_store= def initialize yield(self) if block_given? end def event_stores @event_stores ||= EventStores.new end def event_store=(event_store) @event_stores = EventStores.new(event_store) end def map_types= data @event_stores.map_types data end def snapshot_store @snapshot_store ||= ApplicationSnapshotStore.new end def snapshot_store=(snapshot_store) @snapshot_store = snapshot_store end def snapshot_types= aggregate_types aggregate_types.each do |aggregate_type| aggregate_type.snapshot(true) end end alias_method :event_stores=, :event_store= end end end
ruby
MIT
68b37655c857dd588e950cdcde99056060beaf56
2026-01-04T17:49:58.000055Z
false
Sandthorn/sandthorn
https://github.com/Sandthorn/sandthorn/blob/68b37655c857dd588e950cdcde99056060beaf56/lib/sandthorn/aggregate_root.rb
lib/sandthorn/aggregate_root.rb
require 'sandthorn/aggregate_root_base' require 'sandthorn/aggregate_root_marshal' module Sandthorn module AggregateRoot include Base include Marshal def self.included(base) base.extend(Base::ClassMethods) end end end
ruby
MIT
68b37655c857dd588e950cdcde99056060beaf56
2026-01-04T17:49:58.000055Z
false
Sandthorn/sandthorn
https://github.com/Sandthorn/sandthorn/blob/68b37655c857dd588e950cdcde99056060beaf56/lib/sandthorn/version.rb
lib/sandthorn/version.rb
module Sandthorn VERSION = "1.3.0" end
ruby
MIT
68b37655c857dd588e950cdcde99056060beaf56
2026-01-04T17:49:58.000055Z
false
Sandthorn/sandthorn
https://github.com/Sandthorn/sandthorn/blob/68b37655c857dd588e950cdcde99056060beaf56/lib/sandthorn/aggregate_root_base.rb
lib/sandthorn/aggregate_root_base.rb
module Sandthorn module AggregateRoot module Base attr_reader :aggregate_id attr_reader :aggregate_events attr_reader :aggregate_current_event_version attr_reader :aggregate_originating_version attr_reader :aggregate_trace_information alias :id :aggregate_id alias :aggregate_version :aggregate_current_event_version def aggregate_base_initialize @aggregate_current_event_version = 0 @aggregate_originating_version = 0 @aggregate_events = [] end def save if aggregate_events.any? Sandthorn.save_events( aggregate_events, aggregate_id, self.class ) @aggregate_events = [] @aggregate_originating_version = @aggregate_current_event_version end Sandthorn.save_snapshot self if self.class.snapshot self end def ==(other) other.respond_to?(:aggregate_id) && aggregate_id == other.aggregate_id end def unsaved_events? aggregate_events.any? end def aggregate_trace args @aggregate_trace_information = args yield self if block_given? @aggregate_trace_information = nil end def commit event_name = caller_locations(1,1)[0].label.gsub(/block ?(.*) in /, "") commit_with_event_name(event_name) end def default_attributes #NOOP end alias :record_event :commit module ClassMethods @@aggregate_trace_information = nil def aggregate_trace args @@aggregate_trace_information = args yield self @@aggregate_trace_information = nil end def event_store(event_store = nil) if event_store @event_store = event_store else @event_store end end def snapshot(value = nil) if value @snapshot = value else @snapshot end end def all Sandthorn.all(self).map { |events| aggregate_build events, nil } end def find id return aggregate_find id unless id.respond_to?(:each) return id.map { |e| aggregate_find e } end def aggregate_find aggregate_id begin aggregate_from_snapshot = Sandthorn.find_snapshot(aggregate_id) if self.snapshot current_aggregate_version = aggregate_from_snapshot.nil? ? 0 : aggregate_from_snapshot.aggregate_current_event_version events = Sandthorn.find(aggregate_id, self, current_aggregate_version) if aggregate_from_snapshot.nil? && events.empty? raise Errors::AggregateNotFound end return aggregate_build events, aggregate_from_snapshot rescue Exception raise Errors::AggregateNotFound end end def new *args, &block aggregate = create_new_empty_aggregate() aggregate.aggregate_base_initialize aggregate.aggregate_initialize aggregate.default_attributes aggregate.send :initialize, *args, &block aggregate.send :set_aggregate_id, Sandthorn.generate_aggregate_id aggregate.aggregate_trace @@aggregate_trace_information do |aggr| aggr.send :commit return aggr end end def aggregate_build events, aggregate_from_snapshot = nil aggregate = aggregate_from_snapshot || create_new_empty_aggregate if events.any? current_aggregate_version = events.last[:aggregate_version] aggregate.send :set_orginating_aggregate_version!, current_aggregate_version aggregate.send :set_current_aggregate_version!, current_aggregate_version aggregate.send :set_aggregate_id, events.first.fetch(:aggregate_id) end attributes = build_instance_vars_from_events events aggregate.send :clear_aggregate_events aggregate.default_attributes aggregate.send :aggregate_initialize aggregate.send :set_instance_variables!, attributes aggregate end def stateless_events(*event_names) event_names.each do |name| define_singleton_method name do |aggregate_id, *args| event = build_stateless_event(aggregate_id, name.to_s, args) Sandthorn.save_events([event], aggregate_id, self) return aggregate_id end end end def constructor_events(*event_names) event_names.each do |name| define_singleton_method name do |*args, &block| create_new_empty_aggregate.tap do |aggregate| aggregate.aggregate_base_initialize aggregate.aggregate_initialize aggregate.send :set_aggregate_id, Sandthorn.generate_aggregate_id aggregate.instance_eval(&block) if block aggregate.send :commit_with_event_name, name.to_s return aggregate end end self.singleton_class.class_eval { private name.to_s } end end def events(*event_names) event_names.each do |name| define_method(name) do |*args, &block| block.call() if block commit_with_event_name(name.to_s) end private name.to_s end end private def build_stateless_event aggregate_id, name, args = [] deltas = {} args.first.each do |key, value| deltas[key.to_sym] = { old_value: nil, new_value: value } end unless args.empty? return { aggregate_version: nil, aggregate_id: aggregate_id, event_name: name, event_data: deltas, event_metadata: nil } end def build_instance_vars_from_events events events.each_with_object({}) do |event, instance_vars| attribute_deltas = event[:event_data] unless attribute_deltas.nil? deltas = {} attribute_deltas.each do |key, value| deltas[key] = value[:new_value] end instance_vars.merge! deltas end end end def create_new_empty_aggregate allocate end end private def set_instance_variables! attributes attributes.each_pair do |k,v| self.instance_variable_set "@#{k}", v end end def extract_relevant_aggregate_instance_variables instance_variables.select do |variable| !variable.to_s.start_with?("@aggregate_") end end def set_orginating_aggregate_version! aggregate_version @aggregate_originating_version = aggregate_version end def increase_current_aggregate_version! @aggregate_current_event_version += 1 end def set_current_aggregate_version! aggregate_version @aggregate_current_event_version = aggregate_version end def clear_aggregate_events @aggregate_events = [] end def aggregate_clear_current_event_version! @aggregate_current_event_version = 0 end def set_aggregate_id aggregate_id @aggregate_id = aggregate_id end def commit_with_event_name(event_name) increase_current_aggregate_version! @aggregate_events << ({ aggregate_version: @aggregate_current_event_version, aggregate_id: @aggregate_id, event_name: event_name, event_data: get_delta(), event_metadata: @aggregate_trace_information }) self end end end end
ruby
MIT
68b37655c857dd588e950cdcde99056060beaf56
2026-01-04T17:49:58.000055Z
false
Sandthorn/sandthorn
https://github.com/Sandthorn/sandthorn/blob/68b37655c857dd588e950cdcde99056060beaf56/lib/sandthorn/aggregate_root_marshal.rb
lib/sandthorn/aggregate_root_marshal.rb
module Sandthorn module AggregateRoot module Marshal def aggregate_initialize *args @aggregate_attribute_deltas = {} @aggregate_stored_instance_variables = {} end def set_instance_variables! attribute super attribute init_vars = extract_relevant_aggregate_instance_variables init_vars.each do |attribute_name| @aggregate_stored_instance_variables[attribute_name] = ::Marshal.dump(instance_variable_get(attribute_name)) end end def get_delta deltas = extract_relevant_aggregate_instance_variables deltas.each { |d| delta_attribute(d) } result = @aggregate_attribute_deltas clear_aggregate_deltas result end private def delta_attribute attribute_name old_dump = @aggregate_stored_instance_variables[attribute_name] new_dump = ::Marshal.dump(instance_variable_get(attribute_name)) unless old_dump == new_dump store_attribute_deltas attribute_name, new_dump, old_dump store_aggregate_instance_variable attribute_name, new_dump end end def store_attribute_deltas attribute_name, new_dump, old_dump new_value_to_store = ::Marshal.load(new_dump) old_value_to_store = old_dump ? ::Marshal.load(old_dump) : nil @aggregate_attribute_deltas[attribute_name.to_s.delete("@").to_sym] = { old_value: old_value_to_store, new_value: new_value_to_store } end def store_aggregate_instance_variable attribute_name, new_dump @aggregate_stored_instance_variables[attribute_name] = new_dump end def clear_aggregate_deltas @aggregate_attribute_deltas = {} end end end end
ruby
MIT
68b37655c857dd588e950cdcde99056060beaf56
2026-01-04T17:49:58.000055Z
false
Sandthorn/sandthorn
https://github.com/Sandthorn/sandthorn/blob/68b37655c857dd588e950cdcde99056060beaf56/lib/sandthorn/errors.rb
lib/sandthorn/errors.rb
module Sandthorn module Errors class Error < StandardError; end class AggregateNotFound < Error; end class ConcurrencyError < Error; end class ConfigurationError < Error; end class SnapshotError < Error; end end end
ruby
MIT
68b37655c857dd588e950cdcde99056060beaf56
2026-01-04T17:49:58.000055Z
false
Sandthorn/sandthorn
https://github.com/Sandthorn/sandthorn/blob/68b37655c857dd588e950cdcde99056060beaf56/lib/sandthorn/application_snapshot_store.rb
lib/sandthorn/application_snapshot_store.rb
module Sandthorn class ApplicationSnapshotStore def initialize @store = Hash.new end attr_reader :store def save aggregate_id, aggregate @store[aggregate_id] = aggregate end def find aggregate_id @store[aggregate_id] end end end
ruby
MIT
68b37655c857dd588e950cdcde99056060beaf56
2026-01-04T17:49:58.000055Z
false
Sandthorn/sandthorn
https://github.com/Sandthorn/sandthorn/blob/68b37655c857dd588e950cdcde99056060beaf56/lib/sandthorn/bounded_context.rb
lib/sandthorn/bounded_context.rb
module Sandthorn module BoundedContext module ClassMethods def aggregate_types @aggregate_list = p_aggregate_types(self) end private def p_aggregate_types(bounded_context_module) return [] unless bounded_context_module.respond_to?(:constants) classes = classes_in(bounded_context_module) aggregate_list = classes.select { |item| item.include?(Sandthorn::AggregateRoot) } modules = modules_in(bounded_context_module, classes) aggregate_list += modules.flat_map { |m| p_aggregate_types(m) } aggregate_list end def classes_in(namespace) namespace.constants.map(&namespace.method(:const_get)).grep(Class) end def modules_in(namespace, classes) namespace.constants.map(&namespace.method(:const_get)).grep(Module).delete_if do |m| classes.include?(m) || m == Sandthorn::BoundedContext::ClassMethods end end end extend ClassMethods def self.included( other ) other.extend( ClassMethods ) end end end
ruby
MIT
68b37655c857dd588e950cdcde99056060beaf56
2026-01-04T17:49:58.000055Z
false
Sandthorn/sandthorn
https://github.com/Sandthorn/sandthorn/blob/68b37655c857dd588e950cdcde99056060beaf56/lib/sandthorn/event_inspector.rb
lib/sandthorn/event_inspector.rb
module Sandthorn module EventInspector def has_unsaved_event? event_name, options = {} unsaved = events_with_trace_info if self.aggregate_events.empty? unsaved = [] else unsaved.reject! do |e| e[:aggregate_version] < self .aggregate_events.first[:aggregate_version] end end matching_events = unsaved.select { |e| e[:event_name] == event_name } event_exists = matching_events.length > 0 trace = has_trace? matching_events, options.fetch(:trace, {}) !!(event_exists && trace) end def has_saved_event? event_name, options = {} saved = events_with_trace_info unless self.aggregate_events.empty? saved.reject! do |e| e[:aggregate_version] >= self .aggregate_events.first[:aggregate_version] end end matching_events = saved.select { |e| e[:event_name] == event_name } event_exists = matching_events.length > 0 trace = has_trace? matching_events, options.fetch(:trace, {}) !!(event_exists && trace) end def has_event? event_name, options = {} matching_events = events_with_trace_info .select { |e| e[:event_name] == event_name } event_exists = matching_events.length > 0 trace = has_trace? matching_events, options.fetch(:trace, {}) !!(event_exists && trace) end def events_with_trace_info begin saved = Sandthorn.find aggregate_id, self.class rescue Exception saved = [] end unsaved = self.aggregate_events all = saved .concat(unsaved) .sort { |a, b| a[:aggregate_version] <=> b[:aggregate_version] } extracted = all.collect do |e| if e[:event_data].nil? && !e[:event_data].nil? data = Sandthorn.deserialize e[:event_data] else data = e[:event_data] end { aggregate_version: e[:aggregate_version], event_name: e[:event_name].to_sym, event_data: data, event_metadata: e[:event_metadata] } end extracted end private def get_unsaved_events event_name self.aggregate_events.select { |e| e[:event_name] == event_name.to_s } end def get_saved_events event_name saved_events = Sandthorn.find self.class, self.aggregate_id saved_events.select { |e| e[:event_name] == event_name.to_s } end def has_trace? events_to_check, trace_info return true if trace_info.empty? events_to_check.each do |event| return false if event[:trace] != trace_info end true end end end
ruby
MIT
68b37655c857dd588e950cdcde99056060beaf56
2026-01-04T17:49:58.000055Z
false
Sandthorn/sandthorn
https://github.com/Sandthorn/sandthorn/blob/68b37655c857dd588e950cdcde99056060beaf56/lib/sandthorn/event_stores.rb
lib/sandthorn/event_stores.rb
require 'forwardable' module Sandthorn class EventStores extend Forwardable include Enumerable def_delegators :stores, :each def initialize(stores = nil) @store_map = Hash.new add_initial(stores) end def add(name, event_store) store_map[name] = event_store end alias_method :[]=, :add def add_many(stores) stores.each_pair do |name, store| add(name, store) end end def by_name(name) store_map[name] || default_store end alias_method :[], :by_name def default_store store_map.fetch(:default) end def default_store=(store) store_map[:default] = store end def stores store_map.values end def map_types(hash) hash.each_pair do |event_store, aggregate_types| map_aggregate_types_to_event_store(aggregate_types, event_store) end end private attr_reader :store_map def add_initial(store) if is_event_store?(store) self.default_store = store elsif is_many_event_stores?(store) add_many(store) end end def is_many_event_stores?(store) store.respond_to?(:each_pair) end def is_event_store?(store) store.respond_to?(:get_events) end def map_aggregate_type_to_event_store(aggregate_type, event_store) aggregate_type.event_store(event_store) end def map_aggregate_types_to_event_store(aggregate_types = [], event_store) aggregate_types.each do |aggregate_type| map_aggregate_type_to_event_store(aggregate_type, event_store) end end end end
ruby
MIT
68b37655c857dd588e950cdcde99056060beaf56
2026-01-04T17:49:58.000055Z
false
mainmatter/highlight
https://github.com/mainmatter/highlight/blob/471fec071cd88cca7d29cbcb7c5f774bec883cbc/uninstall.rb
uninstall.rb
puts '' puts " ** Be sure to delete highlight.css from #{RAILS_ROOT}/public/stylesheets/ if you don't need it anymore! **" puts ''
ruby
MIT
471fec071cd88cca7d29cbcb7c5f774bec883cbc
2026-01-04T17:50:00.678204Z
false
mainmatter/highlight
https://github.com/mainmatter/highlight/blob/471fec071cd88cca7d29cbcb7c5f774bec883cbc/rails/init.rb
rails/init.rb
require 'action_view' require 'simplabs/highlight' if `which pygmentize`.blank? puts '' puts " ** [Highlight] pygments cannot be found, falling back to #{Simplabs::Highlight::WEB_API_URL}! **" puts ' ** If you have pygments installed, make sure it is in your PATH. **' puts '' Simplabs::Highlight.use_web_api = true else Simplabs::Highlight.use_web_api = false end ActionView::Base.class_eval do include Simplabs::Highlight::ViewMethods end
ruby
MIT
471fec071cd88cca7d29cbcb7c5f774bec883cbc
2026-01-04T17:50:00.678204Z
false
mainmatter/highlight
https://github.com/mainmatter/highlight/blob/471fec071cd88cca7d29cbcb7c5f774bec883cbc/generators/highlight_styles_generator/highlight_styles_generator.rb
generators/highlight_styles_generator/highlight_styles_generator.rb
if Rails::VERSION::MAJOR >= 3 class HighlightStylesGenerator < Rails::Generators::Base include Rails::Generators::Actions source_root File.expand_path('../templates', __FILE__) def create_stylesheet_file empty_directory('public/stylesheets') copy_file( 'highlight.css', 'public/stylesheets/highlight.css' ) readme(File.join(File.dirname(__FILE__), 'templates', 'NOTES')) end end else class HighlightStylesGenerator < Rails::Generator::Base def manifest record do |m| m.directory('public/stylesheets') m.file('highlight.css', 'public/stylesheets/highlight.css') m.readme('NOTES') end end end end
ruby
MIT
471fec071cd88cca7d29cbcb7c5f774bec883cbc
2026-01-04T17:50:00.678204Z
false
mainmatter/highlight
https://github.com/mainmatter/highlight/blob/471fec071cd88cca7d29cbcb7c5f774bec883cbc/spec/boot.rb
spec/boot.rb
plugin_root = File.join(File.dirname(__FILE__), '..') require File.join(File.dirname(__FILE__), '/../rails/init.rb')
ruby
MIT
471fec071cd88cca7d29cbcb7c5f774bec883cbc
2026-01-04T17:50:00.678204Z
false
mainmatter/highlight
https://github.com/mainmatter/highlight/blob/471fec071cd88cca7d29cbcb7c5f774bec883cbc/spec/spec_helper.rb
spec/spec_helper.rb
$:.reject! { |e| e.include? 'TextMate' } ENV['RAILS_ENV'] = 'test' require 'rubygems' require 'bundler' Bundler.setup require File.join(File.dirname(__FILE__), 'boot')
ruby
MIT
471fec071cd88cca7d29cbcb7c5f774bec883cbc
2026-01-04T17:50:00.678204Z
false
mainmatter/highlight
https://github.com/mainmatter/highlight/blob/471fec071cd88cca7d29cbcb7c5f774bec883cbc/spec/lib/view_methods_spec.rb
spec/lib/view_methods_spec.rb
require 'spec_helper' describe Simplabs::Highlight::ViewMethods do include Simplabs::Highlight::ViewMethods let(:code) { 'class Test; end' } describe '#highlight_code' do describe 'when invoked with a language and a string' do it 'should highlight the code' do Simplabs::Highlight.should_receive(:highlight).once.with(:ruby, code) highlight_code(:ruby, code) end end describe 'when invoked with a language and a block' do it 'should highlight the code' do Simplabs::Highlight.should_receive(:highlight).once.with(:ruby, code) highlight_code(:ruby) do code end end end describe 'when invoked with both a string and a block' do it 'should raise an ArgumentError' do expect { highlight_code(:ruby, code) { code } }.to raise_error(ArgumentError) end end describe 'when invoked with neither a string nor a block' do it 'should raise an ArgumentError' do expect { highlight_code(:ruby) }.to raise_error(ArgumentError) end end end end
ruby
MIT
471fec071cd88cca7d29cbcb7c5f774bec883cbc
2026-01-04T17:50:00.678204Z
false
mainmatter/highlight
https://github.com/mainmatter/highlight/blob/471fec071cd88cca7d29cbcb7c5f774bec883cbc/spec/lib/pygments_wrapper_spec.rb
spec/lib/pygments_wrapper_spec.rb
require 'spec_helper' describe Simplabs::Highlight::PygmentsWrapper do let(:wrapper) do code = <<-EOC class Test def method test end end EOC Simplabs::Highlight::PygmentsWrapper.new(code, :ruby) end describe '#highlight' do it 'should correctly highlight source code passed as parameter' do expect(wrapper.highlight).to eq( %Q(<span class="k">class</span> <span class="nc">Test</span>\n <span class="k">def</span> <span class="nf">method</span> <span class="nb">test</span>\n <span class="k">end</span>\n<span class="k">end</span>) ) end end end
ruby
MIT
471fec071cd88cca7d29cbcb7c5f774bec883cbc
2026-01-04T17:50:00.678204Z
false
mainmatter/highlight
https://github.com/mainmatter/highlight/blob/471fec071cd88cca7d29cbcb7c5f774bec883cbc/spec/lib/highlight_spec.rb
spec/lib/highlight_spec.rb
require 'spec_helper' describe Simplabs::Highlight do let(:code) do <<-EOC class Test def method test end end EOC end describe '#highlight' do shared_examples 'the highlight method' do describe 'when the language is not supported' do it 'should only escape HTML in the passed code' do expect(Simplabs::Highlight.highlight(:unsupported, code)).to eq(CGI.escapeHTML(code)) end end describe 'when the language is supported' do it 'should correctly highlight source code passed as parameter' do expect(Simplabs::Highlight.highlight(:ruby, code)).to eq( %Q(<span class="k">class</span> <span class="nc">Test</span>\n <span class="k">def</span> <span class="nf">method</span> <span class="nb">test</span>\n <span class="k">end</span>\n<span class="k">end</span>) ) end end end describe 'when pygments is used directly' do before do Simplabs::Highlight.use_web_api = false end it_behaves_like 'the highlight method' it 'should initialize a Simplabs::PygmentsWrapper.highlight with the language and code' do wrapper = Simplabs::Highlight::PygmentsWrapper.new(code, :ruby) Simplabs::Highlight::PygmentsWrapper.should_receive(:new).once.with(code, :ruby).and_return(wrapper) Simplabs::Highlight.highlight(:ruby, code) end end describe 'when the web API is used' do before do Simplabs::Highlight.use_web_api = true end it_behaves_like 'the highlight method' end end describe '.get_language_sym' do describe 'for an unsupported language' do it 'should return false' do expect(Simplabs::Highlight.send(:get_language_sym, 'unsupported language')).to be_false end end describe 'for a supported language' do it 'should return the respective symbol when the languages was given as String' do expect(Simplabs::Highlight.send(:get_language_sym, 'ruby')).to eq(:ruby) end it 'should return the respective symbol when the languages was given as Symbol' do expect(Simplabs::Highlight.send(:get_language_sym, :rb)).to eq(:ruby) end end end end
ruby
MIT
471fec071cd88cca7d29cbcb7c5f774bec883cbc
2026-01-04T17:50:00.678204Z
false
mainmatter/highlight
https://github.com/mainmatter/highlight/blob/471fec071cd88cca7d29cbcb7c5f774bec883cbc/lib/simplabs/highlight.rb
lib/simplabs/highlight.rb
require 'cgi' require 'net/http' require 'uri' require 'simplabs/highlight/pygments_wrapper' module Simplabs require 'simplabs/highlight/railtie' if defined?(Rails) && Rails::VERSION::MAJOR >= 3 # Highlight is a simple syntax highlighting plugin for Ruby on Rails. # It's basically a wrapper around the popular http://pygments.org # highlighter that's written in Python and supports an impressive # number of languages. If pygments is installed on the machine and in # the +PATH+, that binary is used, otherwise the plugin falls back # to the web API at (http://pygments.simplabs.com/), created by Trevor # Turk. # # <b>Supported Languages</b> # # The following languages are supported. All of the paranthesized # identifiers may be used as parameters for the +highlight+ method to # denote the language the source code to highlight is written in (use # either Symbols or Strings). # # * Actionscript (+as+, +as3+, +actionscript+) # * Applescript (+applescript+) # * bash (+bash+, +sh+) # * C (+c+, +h+) # * Clojure (+clojure+) # * CoffeeScript (+coffee+) # * C++ (+c+++, +cpp+, +hpp+) # * C# (+c#+, +csharp+, +cs+) # * CSS (+css+) # * diff (+diff+) # * Dylan (+dylan+) # * Erlang (+erlang+, +erl+, +er+) # * HTML (+html+, +htm+) # * Java (+java+) # * JavaScript (+javascript+, +js+, +jscript+) # * JSP (+jsp+) # * Make (+make+, +basemake+, +makefile+) # * NASM (+nasm+, +asm+) # * Objective-C (+objective-c+) # * OCaml (+ocaml+) # * Perl (+perl+, +pl+) # * PHP (+php+) # * Python (+python+, +py+) # * RHTML (+erb+, +rhtml+) # * Ruby (+ruby+, +rb+) # * Scala (+scala+) # * Scheme (+scheme+) # * Smalltalk (+smalltalk+) # * Smarty (+smarty+) # * SQL (+sql+) # * XML (+xml+, +xsd+) # * XSLT (+xslt+) # * YAML (+yaml+, +yml+) # module Highlight class << self attr_accessor :use_web_api end SUPPORTED_LANGUAGES = { :as => ['as', 'as3', 'actionscript'], :applescript => ['applescript'], :bash => ['bash', 'sh'], :c => ['c', 'h'], :clojure => ['clojure'], :coffeescript => ['coffeescript', 'coffee'], :cpp => ['c++', 'cpp', 'hpp'], :csharp => ['c#', 'csharp', 'cs'], :css => ['css'], :diff => ['diff'], :dylan => ['dylan'], :erlang => ['erlang'], :html => ['html', 'htm'], :java => ['java'], :js => ['javascript', 'js', 'jscript'], :jsp => ['jsp'], :lua => ['lua'], :make => ['make', 'basemake', 'makefile'], :nasm => ['nasm', 'asm'], :'objective-c' => ['objective-c'], :ocaml => ['ocaml'], :perl => ['perl', 'pl'], :php => ['php'], :python => ['python', 'py'], :rhtml => ['erb', 'rhtml'], :ruby => ['ruby', 'rb'], :scala => ['scala'], :scheme => ['scheme'], :smallralk => ['smalltalk'], :smarty => ['smarty'], :sql => ['sql', 'mysql'], :xml => ['xml', 'xsd'], :xslt => ['xslt'], :yaml => ['yaml', 'yml'] } WEB_API_URL = 'http://pygments.simplabs.com/' # Highlights the passed +code+ with the appropriate rules # according to the specified +language+. # # @param [Symbol, String] language # the language the +code+ is in # @param [String] code # the actual code to highlight # # @return [String] # the highlighted +code+ or simply the HTML-escaped code if +language+ # is not supported. # def self.highlight(language, code) language = get_language_sym(language) return CGI.escapeHTML(code) unless language if Simplabs::Highlight.use_web_api highlight_with_web_api(language, code) else Simplabs::Highlight::PygmentsWrapper.new(code, language).highlight end end # View Helpers for using {Highlight} in Ruby on Rails templates. # module ViewMethods # Highlights the passed +code+ with the appropriate rules # according to the specified +language+. The code can be specified # either as a string or provided in a block. # # @param [Symbol, String] language # the language the +code+ is in # @param [String] code # the actual code to highlight # @yield # the +code+ can also be specified as result of a given block. # # @return [String] # the highlighted +code+ or simply the HTML-escaped code if +language+ # is not supported. # # @example Specifying the code to highlight as a String # # highlight_code(:ruby, 'class Test; end') # # @example Specifying the code to highlight in a block # # highlight_code(:ruby) do # klass = 'class' # name = 'Test' # _end = 'end' # "#{klass} #{name}; #{_end}" # end # # @raise [ArgumentError] if both the +code+ parameter and a block are given # @raise [ArgumentError] if neither the +code+ parameter or a block are given # # @see Simplabs::Highlight.highlight # def highlight_code(language, code = nil, &block) raise ArgumentError.new('Either pass a srting containing the code or a block, not both!') if !code.nil? && block_given? raise ArgumentError.new('Pass a srting containing the code or a block!') if code.nil? && !block_given? code ||= yield Simplabs::Highlight.highlight(language, code) end end private def self.highlight_with_web_api(language, code) request = Net::HTTP.post_form(URI.parse(WEB_API_URL), { 'lang' => language, 'code' => code }) request.body.gsub(/\A\<div class=\"highlight\"\>\<pre\>/, '').gsub(/\n\<\/pre\>\<\/div\>\n/, '') end def self.get_language_sym(name) SUPPORTED_LANGUAGES.each_pair do |key, value| return key if value.any? { |lang| lang == name.to_s } end return false end end end
ruby
MIT
471fec071cd88cca7d29cbcb7c5f774bec883cbc
2026-01-04T17:50:00.678204Z
false
mainmatter/highlight
https://github.com/mainmatter/highlight/blob/471fec071cd88cca7d29cbcb7c5f774bec883cbc/lib/simplabs/highlight/railtie.rb
lib/simplabs/highlight/railtie.rb
require 'simplabs/highlight' require 'rails' module Simplabs module Highlight class Railtie < Rails::Railtie GEM_ROOT = File.join(File.dirname(__FILE__), '..', '..', '..') initializer 'simplabs.highlight.initialization' do require File.join(GEM_ROOT, 'rails', 'init') end generators do require File.join(GEM_ROOT, 'generators', 'highlight_styles_generator', 'highlight_styles_generator') end end end end
ruby
MIT
471fec071cd88cca7d29cbcb7c5f774bec883cbc
2026-01-04T17:50:00.678204Z
false
mainmatter/highlight
https://github.com/mainmatter/highlight/blob/471fec071cd88cca7d29cbcb7c5f774bec883cbc/lib/simplabs/highlight/pygments_wrapper.rb
lib/simplabs/highlight/pygments_wrapper.rb
module Simplabs module Highlight # Wraps the actual +pygments+ syntax highlighter and # exposes its functionality to Ruby code. # class PygmentsWrapper # The code the wrapper highlights # attr_reader :code # The language the {Simplabs::Highlight::PygmentsWrapper#code} to highlight is in # attr_reader :language # Initializes a new {Simplabs::Highlight::PygmentsWrapper}. # # @param [String] code # the actual code to highlight # @param [String, Symbol] language # the language the +code+ to highlight is in # def initialize(code, language) @code = code @language = language end # Highlights the {Simplabs::Highlight::PygmentsWrapper#code}. # # @return [String] # the highlighted code or simply the HTML-escaped code # if the language is not supported. # def highlight(options = {}) command = "pygmentize -f html -O nowrap=true -l #{@language}" IO.popen(command, mode = 'r+') do |pygments| pygments << @code pygments.close_write result = pygments.read.chomp end end end end end
ruby
MIT
471fec071cd88cca7d29cbcb7c5f774bec883cbc
2026-01-04T17:50:00.678204Z
false
sblackstone/auto_sprite
https://github.com/sblackstone/auto_sprite/blob/c54076cf419e7b7fdeddb5d25a1d3b87533376c1/rails/init.rb
rails/init.rb
require 'auto_sprite' AutoSprite.setup! ActionView::Helpers.send(:include, AutoSprite::Helpers)
ruby
MIT
c54076cf419e7b7fdeddb5d25a1d3b87533376c1
2026-01-04T17:50:07.321106Z
false
sblackstone/auto_sprite
https://github.com/sblackstone/auto_sprite/blob/c54076cf419e7b7fdeddb5d25a1d3b87533376c1/lib/auto_sprite.rb
lib/auto_sprite.rb
require 'RMagick' require 'fileutils' module AutoSprite SPRITE_ASSETS_PATH = File.join(RAILS_ROOT, 'public', 'images', 'sprites') CSS_FILE_PATH = File.join(RAILS_ROOT, 'public', 'stylesheets', 'auto_sprite.css') SPRITE_IMG_PATH = File.join(RAILS_ROOT, 'public', 'images', 'auto_sprite.png') SPRITE_IMG_URL = '/images/auto_sprite.png' class << self def sprite_file_paths @sprite_file_paths ||= sprite_file_names.map {|f| File.join(SPRITE_ASSETS_PATH, f) } end def sprite_file_names @sprite_file_names ||= Dir.entries(SPRITE_ASSETS_PATH).reject { |f| !File.file?(File.join(SPRITE_ASSETS_PATH,f)) } end def generate_css_name(f) filename = File.basename(f).gsub(/\?.*$/, "") filename.tr!('.', "_") "_as_#{filename}" end def stale? to_check = [sprite_file_paths , SPRITE_ASSETS_PATH].flatten !FileUtils.uptodate?(SPRITE_IMG_PATH , to_check) || !FileUtils.uptodate?(CSS_FILE_PATH , to_check) end def setup! FileUtils::mkdir_p(SPRITE_ASSETS_PATH) if stale? FileUtils::rm_f(CSS_FILE_PATH) FileUtils::rm_f(SPRITE_IMG_PATH) write_new_assets end end def write_new_assets unless sprite_file_paths.empty? image_list = Magick::ImageList.new(*sprite_file_paths) image_list.append(true).write(SPRITE_IMG_PATH) all_class_names = sprite_file_names.map { |x| '.' + generate_css_name(x) } pos = 0 File.open(CSS_FILE_PATH, "w") do |f| image_list.each do |img| css_class = generate_css_name(img.filename) f << ".#{css_class}{background-position:0 #{pos * -1}px;height:#{img.rows}px;width:#{img.columns}px;}" pos = pos + img.rows; end f << all_class_names.join(",") f << "{display:inline-block;background-image:url('#{SPRITE_IMG_URL}?#{File.mtime(SPRITE_IMG_PATH).to_i}');background-repeat:no-repeat;}" end end end end end module AutoSprite::Helpers def self.included(base) base.class_eval do def image_tag(source, options = {}) src = path_to_image(source) if src =~ /\/images\/sprites/ content_tag :span, '', options.merge(:class => AutoSprite.generate_css_name(src)) else super(source,options) end end end end end
ruby
MIT
c54076cf419e7b7fdeddb5d25a1d3b87533376c1
2026-01-04T17:50:07.321106Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/spec/engineyard_spec.rb
spec/engineyard_spec.rb
require 'spec_helper' describe EY do it "provides EY errors" do expect(EY::Error).to be end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/spec/spec_helper.rb
spec/spec_helper.rb
if self.class.const_defined?(:EY_ROOT) raise "don't require the spec helper twice!" end if ENV['COVERAGE'] require 'simplecov' SimpleCov.start end EY_ROOT = File.expand_path("../..", __FILE__) require 'rubygems' require 'bundler/setup' require 'escape' require 'net/ssh' # Bundled gems require 'fakeweb' require 'fakeweb_matcher' require 'multi_json' # Engineyard gem $LOAD_PATH.unshift(File.join(EY_ROOT, "lib")) require 'engineyard' require 'engineyard-cloud-client/test' # Spec stuff require 'rspec' require 'tmpdir' require 'yaml' require 'pp' Dir[File.join(EY_ROOT,'/spec/support/*.rb')].each do |helper| require helper end TMPDIR = Pathname.new(__FILE__).dirname.parent.join('tmp') RSpec.configure do |config| config.treat_symbols_as_metadata_keys_with_true_values = true config.run_all_when_everything_filtered = true config.include SpecHelpers config.include SpecHelpers::IntegrationHelpers config.extend SpecHelpers::GitRepoHelpers config.extend SpecHelpers::Given def clean_tmpdir TMPDIR.rmtree if TMPDIR.exist? end # Cleaning the tmpdir has to happen outside of the test cycle because git repos # last longer than the before/after :all test block in order to speed up specs. config.before(:suite) { clean_tmpdir } config.after(:suite) { clean_tmpdir } config.before(:all) do clean_eyrc FakeWeb.allow_net_connect = false ENV["CLOUD_URL"] = nil ENV["NO_SSH"] = "true" end config.after(:all) do clean_eyrc end end shared_examples_for "integration" do use_git_repo('default') before(:all) do FakeWeb.allow_net_connect = true ENV['CLOUD_URL'] = EY::CloudClient::Test::FakeAwsm.uri end after(:all) do ENV.delete('CLOUD_URL') FakeWeb.allow_net_connect = false end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/spec/support/matchers.rb
spec/support/matchers.rb
require 'rspec/matchers' RSpec::Matchers.define :have_command_like do |regex| match do |command_list| @found = command_list.find{|c| c =~ regex } !!@found end failure_message_for_should do |command_list| "Didn't find a command matching #{regex} in commands:\n\n" + command_list.join("\n\n") end failure_message_for_should_not do |command_list| "Found unwanted command:\n\n#{@found}\n\n(matches regex #{regex})" end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/spec/support/ruby_ext.rb
spec/support/ruby_ext.rb
module Kernel def capture_stdio(input = nil, &block) require 'stringio' org_stdin, $stdin = $stdin, StringIO.new(input) if input org_stdout, $stdout = $stdout, StringIO.new yield return @out = $stdout.string ensure $stdout = org_stdout $stdin = org_stdin end alias capture_stdout capture_stdio end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/spec/support/git_repos.rb
spec/support/git_repos.rb
module EY class << self def define_git_repo(name, &setup) git_repo_setup[name] ||= setup end def refresh_git_repo(name) git_repo_dir_cache.delete name end def git_repo_dir(name) return git_repo_dir_cache[name] if git_repo_dir_cache.has_key?(name) raise ArgumentError, "No definition for git repo #{name}" unless git_repo_setup[name] git_dir = TMPDIR.join("engineyard_test_repo_#{Time.now.tv_sec}_#{Time.now.tv_usec}_#{$$}") git_dir.mkpath Dir.chdir(git_dir) do system("git init -q") system('git config user.email ey@spec.test') system('git config user.name "EY Specs"') system("git remote add testremote user@git.host:path/to/repo.git") git_repo_setup[name].call(git_dir) end git_repo_dir_cache[name] = git_dir end def chdir_to_repo(repo_name) @_original_wd ||= [] @_original_wd << Dir.getwd Dir.chdir(git_repo_dir(repo_name)) end def chdir_return Dir.chdir(@_original_wd.pop) if @_original_wd && @_original_wd.any? end def fixture_recipes_tgz File.expand_path('../fixture_recipes.tgz', __FILE__) end def link_recipes_tgz(git_dir) system("ln -s #{fixture_recipes_tgz} #{git_dir.join('recipes.tgz')}") end protected def git_repo_setup @git_repo_setup ||= {} end def git_repo_dir_cache @git_repo_dir_cache ||= {} end end define_git_repo("default") do |git_dir| system("echo 'source :gemcutter' > Gemfile") system("git add Gemfile") system("git commit -m 'initial commit' >/dev/null 2>&1") end define_git_repo('deploy test') do # we'll have one commit on master system("echo 'source :gemcutter' > Gemfile") system("git add Gemfile") system("git commit -m 'initial commit' >/dev/null 2>&1") # and a tag system("git tag -a -m 'version one' v1") # and we need a non-master branch system("git checkout -b current-branch >/dev/null 2>&1") end define_git_repo('+cookbooks') do |git_dir| git_dir.join("cookbooks").mkdir git_dir.join("cookbooks/file").open("w") {|f| f << "boo" } end define_git_repo('+recipes') do |git_dir| link_recipes_tgz(git_dir) end define_git_repo "only cookbooks, no remotes" do |git_dir| `git --git-dir "#{git_dir}/.git" remote`.split("\n").each do |remote| `git --git-dir "#{git_dir}/.git" remote rm #{remote}` end git_dir.join("cookbooks").mkdir File.open(git_dir.join("cookbooks/file"), "w"){|f| f << "stuff" } end define_git_repo "only cookbooks, unrelated remotes" do |git_dir| `git --git-dir "#{git_dir}/.git" remote`.split("\n").each do |remote| `git --git-dir "#{git_dir}/.git" remote rm #{remote}` end `git remote add origin polly@pirate.example.com:wanna/cracker.git` git_dir.join("cookbooks").mkdir File.open(git_dir.join("cookbooks/file"), "w"){|f| f << "rawk" } end define_git_repo('dup test') do system("git remote add dup git://github.com/engineyard/dup.git") end define_git_repo("not actually a git repo") do |git_dir| # in case we screw up and are not in a freshly-generated test # git repository, don't blow away the thing we're developing system("rm -rf .git") if `git remote -v`.include?("path/to/repo.git") git_dir.join("cookbooks").mkdir link_recipes_tgz(git_dir) end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/spec/support/helpers.rb
spec/support/helpers.rb
require 'engineyard/cli' require 'realweb' require 'open4' require 'stringio' module SpecHelpers module Given def given(name) include_examples name end end module IntegrationHelpers def run_ey(command_options, ey_options={}) if respond_to?(:extra_ey_options) # needed for ssh tests ey_options.merge!(extra_ey_options) return ey(command_to_run(command_options), ey_options) end if ey_options[:expect_failure] fast_failing_ey(command_to_run(command_options)) else fast_ey(command_to_run(command_options)) end end def make_scenario(opts) # since nil will silently turn to empty string when interpolated, # and there's a lot of string matching involved in integration # testing, it would be nice to have early notification of typos. scenario = Hash.new { |h,k| raise "Tried to get key #{k.inspect}, but it's missing!" } scenario.merge!(opts) end end module GitRepoHelpers def define_git_repo(name, &setup) # EY's ivars don't get cleared between examples, so we can keep # a git repo around longer (and thus make our tests faster) EY.define_git_repo(name, &setup) end def use_git_repo(repo_name) before(:all) do EY.chdir_to_repo(repo_name) end after(:all) do EY.chdir_return end end end class UnexpectedExit < StandardError def initialize(stdout, stderr) super "Exited with an unexpected exit code\n---STDOUT---\n#{stdout}\n---STDERR---\n#{stderr}\n" end end NonzeroExitStatus = Class.new(UnexpectedExit) ZeroExitStatus = Class.new(UnexpectedExit) def ey_api @api ||= EY::CloudClient.new(:token => 'asdf') end def ensure_eyrc begin unless (data = read_eyrc) and data['api_token'] raise ".eyrc has no token, specs will stall waiting for stdin authentication input" end rescue Errno::ENOENT => e raise ".eyrc must be written before calling run_ey or specs will stall waiting for stdin authentication input" end end def fast_ey(args, options = {}) ensure_eyrc begin debug = options[:debug] ? 'true' : nil err, out = StringIO.new, StringIO.new capture_stderr_into(err) do capture_stdout_into(out) do with_env('DEBUG' => debug, 'PRINT_CMD' => 'true') do EY::CLI.start(args) end end end ensure @err, @out = err.string, out.string @raw_ssh_commands, @ssh_commands = extract_ssh_commands(@out) end end def fast_failing_ey(*args) begin fast_ey(*args) raise ZeroExitStatus.new(@out, @err) rescue SystemExit => exit_status # SystemExit typically indicates a bogus command, which we # here in expected-to-fail land are entirely happy with. nil rescue Thor::Error, EY::Error, EY::CloudClient::Error => e nil end end def capture_stderr_into(stream) $stderr = stream yield ensure $stderr = STDERR end def capture_stdout_into(stream) $stdout = stream yield ensure $stdout = STDOUT end def ey(args = [], options = {}, &block) if respond_to?(:extra_ey_options) # needed for ssh tests options.merge!(extra_ey_options) end hide_err = options.has_key?(:hide_err) ? options[:hide_err] : options[:expect_failure] path_prepends = options[:prepend_to_path] ey_env = { 'DEBUG' => ENV['DEBUG'], 'PRINT_CMD' => 'true', 'EYRC' => ENV['EYRC'], 'CLOUD_URL' => ENV['CLOUD_URL'], } if options.has_key?(:debug) ey_env['DEBUG'] = options[:debug] ? "true" : nil end if path_prepends tempdir = TMPDIR.join("ey_test_cmds_#{Time.now.tv_sec}#{Time.now.tv_usec}_#{$$}") tempdir.mkpath path_prepends.each do |name, contents| tempdir.join(name).open('w') do |f| f.write(contents) f.chmod(0755) end end ey_env['PATH'] = "#{tempdir}:#{ENV['PATH']}" end eybin = File.expand_path('../bundled_ey legacy', __FILE__) with_env(ey_env) do exit_status = Open4::open4("#{eybin} #{Escape.shell_command(args)}") do |pid, stdin, stdout, stderr| block.call(stdin) if block stdin.close @out = stdout.read @err = stderr.read end if !exit_status.success? && !options[:expect_failure] raise NonzeroExitStatus.new(@out, @err) elsif exit_status.success? && options[:expect_failure] raise ZeroExitStatus.new(@out, @err) end end @raw_ssh_commands, @ssh_commands = extract_ssh_commands(@out) puts @err unless @err.empty? || hide_err @out end def extract_ssh_commands(output) raw_ssh_commands = [@out,@err].join("\n").split(/\n/).find_all do |line| line =~ /^bash -lc/ || line =~ /^ssh/ || line =~ /^scp/ end ssh_commands = raw_ssh_commands.map do |cmd| # Strip off everything up to and including user@host, leaving # just the command that the remote system would run # # XXX: this is a really icky icky. # engineyard gem was written as if shelling out to run serverside # and running an ssh command will always be the same. This is a nasty # hack to get it working with Net::SSH for now so we can repair 1.9.2. ssh_prefix_removed = cmd.gsub(/^bash -lc /, '').gsub(/^ssh .*?\w+@\S*\s*/, '') # Its arguments have been double-escaped: one layer is to get # them through our local shell and into ssh, and the other # layer is to get them through the remote system's shell. # # Strip off one layer by running it through the shell. just_the_remote_command = ssh_prefix_removed.gsub(/>\s*\/dev\/null.*$/, '') `echo #{just_the_remote_command}`.strip end [raw_ssh_commands, ssh_commands] end DEPRECATED_SCENARIOS = { "empty" => "User Name", "one app without environment" => "App Without Env", "one app, one environment, not linked" => "Unlinked App", "two apps" => "Two Apps", "one app, one environment" => "Linked App", "Stuck Deployment" => "Stuck Deployment", "two accounts, two apps, two environments, ambiguous" => "Multiple Ambiguous Accounts", "one app, one environment, no instances" => "Linked App Not Running", "one app, one environment, app master red" => "Linked App Red Master", "one app, many environments" => "One App Many Envs", "one app, many similarly-named environments" => "One App Similarly Named Envs", "two apps, same git uri" => "Two Apps Same Git URI", } def api_scenario(old_name) clean_eyrc # switching scenarios, always clean up name = DEPRECATED_SCENARIOS[old_name] @scenario = EY::CloudClient::Test::Scenario[name] @scenario_email = @scenario.email @scenario_password = @scenario.password @scenario_api_token = @scenario.api_token @scenario end def login_scenario(scenario_name) scen = api_scenario(scenario_name) write_eyrc('api_token' => scenario_api_token) scen end def scenario_email @scenario_email end def scenario_password @scenario_password end def scenario_api_token @scenario_api_token end def clean_tmpdir TMPDIR.rmtree if TMPDIR.exist? end def read_yaml(file) contents = File.read(File.expand_path(file)) YAML.load(contents) rescue Exception => e raise "#{e}\n#{contents}" end def write_yaml(data, file) File.open(file, "w"){|f| YAML.dump(data, f) } end def clean_eyrc ENV['EYRC'] = File.join('/tmp','eyrc') if ENV['EYRC'] && File.exist?(ENV['EYRC']) File.unlink(ENV['EYRC']) end end def read_eyrc read_yaml(ENV['EYRC']) end def write_eyrc(data) write_yaml(data, ENV['EYRC']) end def ey_yml EY::Config.pathname end def clean_ey_yml ey_yml.unlink if ey_yml && ey_yml.exist? FileUtils.rm_r 'config' if FileTest.exist?('config') end def read_ey_yml read_yaml(EY::Config.pathname) end def write_ey_yml(data) write_yaml(data, EY::Config.pathname_for_write) end def expect_config(*keys) root = keys.unshift('defaults') unless %w[defaults environments].include?(keys.first) config = read_ey_yml value = keys.inject(config) { |conf, key| conf[key] } expect(value) end def exist be_exist end def with_env(new_env_vars) raise ArgumentError, "with_env takes a block" unless block_given? old_env_vars = {} new_env_vars.each do |k, v| if ENV.has_key?(k) old_env_vars[k] = ENV[k] end ENV[k] = v if v end retval = yield new_env_vars.keys.each do |k| if old_env_vars.has_key?(k) ENV[k] = old_env_vars[k] else ENV.delete(k) end end retval end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/spec/support/shared_behavior.rb
spec/support/shared_behavior.rb
require 'ostruct' shared_examples_for "it has an ambiguous git repo" do use_git_repo('dup test') before(:all) do login_scenario "two apps, same git uri" end end shared_examples_for "it requires an unambiguous git repo" do include_examples "it has an ambiguous git repo" it "lists disambiguating environments to choose from" do run_ey({}, {:expect_failure => true}) expect(@err).to include('Multiple environments possible, please be more specific') expect(@err).to match(/giblets/) expect(@err).to match(/keycollector_production/) end end shared_examples_for "it takes an environment name and an app name and an account name" do include_examples "it takes an app name" include_examples "it takes an environment name" it "complains when you send --account without a value" do login_scenario "empty" fast_failing_ey command_to_run({}) << '--account' expect(@err).to include("No value provided for option '--account'") fast_failing_ey command_to_run({}) << '-c' expect(@err).to include("No value provided for option '--account'") end context "when multiple accounts with collaboration" do before :all do login_scenario "two accounts, two apps, two environments, ambiguous" end it "fails when the app and environment are ambiguous across accounts" do run_ey({:environment => "giblets", :app => "rails232app", :ref => 'master'}, {:expect_failure => !@succeeds_on_multiple_matches}) if @succeeds_on_multiple_matches expect(@err).not_to match(/multiple/i) else expect(@err).to match(/Multiple application environments possible/i) expect(@err).to match(/ey \S+ --account='account_2' --app='rails232app' --environment='giblets'/i) expect(@err).to match(/ey \S+ --account='main' --app='rails232app' --environment='giblets'/i) end end it "runs when specifying the account disambiguates the app to deploy" do run_ey({:environment => "giblets", :app => "rails232app", :account => "main", :ref => 'master'}) verify_ran(make_scenario({ :environment => 'giblets', :application => 'rails232app', :master_hostname => 'app_master_hostname.compute-1.amazonaws.com', :ssh_username => 'turkey', })) end end end shared_examples_for "it takes an environment name and an account name" do include_examples "it takes an environment name" it "complains when you send --account without a value" do login_scenario "empty" fast_failing_ey command_to_run({}) << '--account' expect(@err).to include("No value provided for option '--account'") fast_failing_ey command_to_run({}) << '-c' expect(@err).to include("No value provided for option '--account'") end context "when multiple accounts with collaboration" do before :all do login_scenario "two accounts, two apps, two environments, ambiguous" end it "fails when the app and environment are ambiguous across accounts" do run_ey({:environment => "giblets"}, {:expect_failure => true}) expect(@err).to match(/multiple environments possible/i) expect(@err).to match(/ey \S+ --environment='giblets' --account='account_2'/i) expect(@err).to match(/ey \S+ --environment='giblets' --account='main'/i) end it "runs when specifying the account disambiguates the app to deploy" do run_ey({:environment => "giblets", :account => "main"}) verify_ran(make_scenario({ :environment => 'giblets', :account => 'main', :application => 'rails232app', :master_hostname => 'app_master_hostname.compute-1.amazonaws.com', :ssh_username => 'turkey', })) end context "when the backend raises an error" do before do # FIXME, cloud-client needs to provide an API for making responses raise allow(EY::CLI::API).to receive(:new).and_raise(EY::CloudClient::RequestFailed.new("Error: Important infos")) end it "returns the error message to the user" do fast_failing_ey(command_to_run({:environment => "giblets", :account => "main"})) expect(@err).to match(/Important infos/) end end end end shared_examples_for "it takes an environment name" do it "operates on the current environment by default" do login_scenario "one app, one environment" run_ey(:environment => nil) verify_ran(make_scenario({ :environment => 'giblets', :account => 'main', :application => 'rails232app', :master_hostname => 'app_master_hostname.compute-1.amazonaws.com', :ssh_username => 'turkey', })) end it "complains when you specify a nonexistent environment" do login_scenario "one app, one environment" # This test must shell out (not sure why, plz FIXME) ey command_to_run(:environment => 'typo-happens-here'), {:expect_failure => true} expect(@err).to match(/No environment found matching .*typo-happens-here/i) end it "complains when you send --environment without a value" do login_scenario "empty" fast_failing_ey command_to_run({}) << '--environment' expect(@err).to include("No value provided for option '--environment'") fast_failing_ey command_to_run({}) << '-e' expect(@err).to include("No value provided for option '--environment'") end context "outside a git repo" do use_git_repo("not actually a git repo") before :all do login_scenario "one app, one environment" end it "works (and does not complain about git remotes)" do run_ey({:environment => 'giblets'}) unless @takes_app_name end end context "given a piece of the environment name" do before(:all) do login_scenario "one app, many similarly-named environments" end it "complains when the substring is ambiguous" do run_ey({:environment => 'staging'}, {:expect_failure => !@succeeds_on_multiple_matches}) if @succeeds_on_multiple_matches expect(@err).not_to match(/multiple .* possible/i) else if @takes_app_name expect(@err).to match(/multiple application environments possible/i) else expect(@err).to match(/multiple environments possible/i) end end end it "works when the substring is unambiguous" do login_scenario "one app, many similarly-named environments" run_ey({:environment => 'prod', :migrate => 'rake db:migrate'}, {:debug => true}) verify_ran(make_scenario({ :environment => 'railsapp_production', :application => 'rails232app', :account => 'main', :master_hostname => 'app_master_hostname.compute-1.amazonaws.com', :ssh_username => 'turkey', })) end end it "complains when it can't guess the environment and its name isn't specified" do login_scenario "one app without environment" run_ey({:environment => nil}, {:expect_failure => true}) expect(@err).to match(/No environment found for applications matching remotes:/i) end end shared_examples_for "it takes an app name" do before { @takes_app_name = true } it "complains when you send --app without a value" do login_scenario "empty" fast_failing_ey command_to_run({}) << '--app' expect(@err).to include("No value provided for option '--app'") fast_failing_ey command_to_run({}) << '-a' expect(@err).to include("No value provided for option '--app'") end it "allows you to specify a valid app" do login_scenario "one app, one environment" Dir.chdir(Dir.tmpdir) do run_ey({:environment => 'giblets', :app => 'rails232app', :ref => 'master', :migrate => nil}, {}) verify_ran(make_scenario({ :environment => 'giblets', :application => 'rails232app', :master_hostname => 'app_master_hostname.compute-1.amazonaws.com', :ssh_username => 'turkey', })) end end it "can guess the environment from the app" do login_scenario "two apps" Dir.chdir(Dir.tmpdir) do run_ey({:app => 'rails232app', :ref => 'master', :migrate => true}, {}) verify_ran(make_scenario({ :environment => 'giblets', :application => 'rails232app', :master_hostname => 'app_master_hostname.compute-1.amazonaws.com', :ssh_username => 'turkey', })) end end it "complains when you specify a nonexistant app" do login_scenario "one app, one environment" run_ey({:environment => 'giblets', :app => 'P-time-SAT-solver', :ref => 'master'}, {:expect_failure => true}) expect(@err).to match(/No app.*P-time-SAT-solver/i) end end shared_examples_for "it invokes engineyard-serverside" do context "with arguments" do before(:all) do login_scenario "one app, one environment" run_ey({:environment => 'giblets', :verbose => true}) end it "passes --verbose to engineyard-serverside" do expect(@ssh_commands).to have_command_like(/engineyard-serverside.*--verbose/) end it "passes along instance information to engineyard-serverside" do instance_args = [ /--instances app_hostname[^\s]+ localhost util_fluffy/, /--instance-roles app_hostname[^\s]+:app localhost:app_master util_fluffy[^\s]+:util/, /--instance-names util_fluffy_hostname[^\s]+:fluffy/ ] db_instance = /db_master/ # apps + utilities are all mentioned instance_args.each do |i| expect(@ssh_commands.last).to match(/#{i}/) end # but not database instances expect(@ssh_commands.last).not_to match(/#{db_instance}/) end end context "when no instances have names" do before(:each) do login_scenario "two apps" run_ey({:env => 'giblets', :app => 'rails232app', :ref => 'master', :migrate => true, :verbose => true}) end it "omits the --instance-names parameter" do expect(@ssh_commands.last).not_to include("--instance-names") end end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/spec/engineyard/eyrc_spec.rb
spec/engineyard/eyrc_spec.rb
require 'spec_helper' require 'engineyard/eyrc' describe EY::EYRC do before { clean_eyrc } describe ".load" do it "looks for .eyrc in $EYRC if set" do expect(EY::EYRC.load.path).to eq(Pathname.new(ENV['EYRC'])) end it "looks for .eyrc in $HOME/.eyrc by default" do ENV.delete('EYRC') expect(EY::EYRC.load.path).to eq(Pathname.new("#{ENV['HOME']}/.eyrc")) end end describe ".new" do it "looks for eyrc in any passed file location" do expect(EY::EYRC.new('/tmp/neweyrc').path).to eq(Pathname.new('/tmp/neweyrc')) end end context "with a non-existing .eyrc file" do it "has nil api_token" do expect(File.exists?("/tmp/nonexistant")).to be_falsey eyrc = EY::EYRC.new('/tmp/nonexistant') expect(eyrc.exist?).to be_falsey expect(eyrc.api_token).to be_nil end end context "saving api token" do before do EY::EYRC.load.api_token = 'abcd' end it "exists" do expect(EY::EYRC.load.exist?).to be_truthy end it "recalls the api_token" do expect(EY::EYRC.load.api_token).to eq('abcd') end it "deletes the api_token" do EY::EYRC.load.delete_api_token expect(EY::EYRC.load.api_token).to be_nil end it "writes the api_token to api_token: .eyrc" do expect(read_yaml(ENV['EYRC'])).to eq({"api_token" => "abcd"}) end end context "file contains other random info" do before do # contains legacy endpoint behavior, no longer supported, but we won't be destructive. write_yaml({"api_token" => "1234", "http://localhost/" => {"api_token" => "5678"}}, ENV['EYRC']) EY::EYRC.load.api_token = 'abcd' # overwrites 1234 end it "recalls the api_token" do expect(EY::EYRC.load.api_token).to eq('abcd') end it "deletes the api token safely on logout" do EY::EYRC.load.delete_api_token expect(read_yaml(ENV['EYRC'])).to eq({"http://localhost/" => {"api_token" => "5678"}}) end it "maintains other random info in the file" do expect(read_yaml(ENV['EYRC'])).to eq({"api_token" => "abcd", "http://localhost/" => {"api_token" => "5678"}}) end end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/spec/engineyard/repo_spec.rb
spec/engineyard/repo_spec.rb
require 'spec_helper' describe EY::Repo do let(:path) { p = TMPDIR.join('ey-test'); p.mkpath; p } before(:each) do Dir.chdir(path) { `git init -q` } ENV['GIT_DIR'] = path.join('.git').to_s end after(:each) do path.rmtree ENV.delete('GIT_DIR') end def set_head(head) path.join('.git','HEAD').open('w') {|f| f.write(head) } end def set_url(url, remote) `git remote add #{remote} #{url}` end describe ".new" do it "creates a working repo object in a repo" do expect(EY::Repo.new.remotes).to be_empty end it "doesn't raise if created outside a repository until trying to do something" do ENV['GIT_DIR'] = nil Dir.chdir('/tmp') do repo = EY::Repo.new expect { repo.remotes }.to raise_error(EY::Repo::NotAGitRepository) end end end describe ".exist?" do it "is true when env vars are set to a repo" do expect(EY::Repo).to be_exist end it "is true when pwd is a repo" do Dir.chdir(File.dirname(ENV['GIT_DIR'])) do ENV['GIT_DIR'] = nil expect(EY::Repo).to be_exist end end it "is false when outside of any repo" do ENV['GIT_DIR'] = nil Dir.chdir('/tmp') do expect(EY::Repo).not_to be_exist end end end context "in a repository dir" do before(:each) do @repo = EY::Repo.new end describe "current_branch method" do it "returns the name of the current branch" do set_head "ref: refs/heads/master" expect(@repo.current_branch).to eq("master") end it "returns nil if there is no current branch" do set_head "20bf478ab6a91ec5771130aa4c8cfd3d150c4146" expect(@repo.current_branch).to be_nil end end # current_branch describe "#fail_on_no_remotes!" do it "raises when there are no remotes" do expect { @repo.fail_on_no_remotes! }.to raise_error(EY::Repo::NoRemotesError) end end end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/spec/engineyard/cli_spec.rb
spec/engineyard/cli_spec.rb
require 'spec_helper' require 'engineyard/cli' describe EY::CLI do it "provides help" do out = capture_stdout do EY::CLI.start(["help"]) end expect(out).to include("ey deploy") expect(out).to include("ey ssh") expect(out).to include("ey web enable") end it "delegates help" do out = capture_stdout do EY::CLI.start(%w[help web enable]) end expect(out).to match(/remove the maintenance page/i) end it "provides error classes" do expect(EY::DeployArgumentError).to be end end # EY::CLI
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/spec/engineyard/deploy_config_spec.rb
spec/engineyard/deploy_config_spec.rb
require 'spec_helper' require 'tempfile' describe EY::DeployConfig do let(:tempfile) { @tempfile = Tempfile.new('ey.yml') } let(:parent) { EY::Config.new(tempfile.path) } let(:ui) { EY::CLI::UI.new } let(:repo) { double('repo') } let(:env) { env_config(nil) } after { @tempfile.unlink if @tempfile } def env_config(opts, config = parent) EY::Config::EnvironmentConfig.new(opts, 'envname', config) end def deploy_config(cli_opts, ec = env) EY::DeployConfig.new(cli_opts, ec, repo, ui) end context "inside a repository" do context "with no ey.yml file" do let(:env) { env_config(nil, EY::Config.new('noexisto.yml')) } it "tells you to initialize a new repository with ey init" do dc = deploy_config({}, env) expect { dc.migrate }.to raise_error(EY::Error, /Please initialize this application with the following command:/) end end context "with the migrate cli option" do it "returns default command when true" do dc = deploy_config({'migrate' => true}) expect(dc.migrate).to be_truthy expect { dc.migrate_command }.to raise_error(EY::Error, /'migration_command' not found/) end it "returns false when nil" do dc = deploy_config({'migrate' => nil}) expect(dc.migrate).to be_falsey expect(dc.migrate_command).to be_nil end it "return the custom migration command when is a string" do dc = deploy_config({'migrate' => 'foo migrate'}) expect(dc.migrate).to be_truthy expect(dc.migrate_command).to eq('foo migrate') end end context "with the migrate option in the global configuration" do it "return the migration command when the option is true" do env = env_config('migrate' => true, 'migration_command' => 'bar migrate') dc = deploy_config({}, env) expect(dc.migrate).to be_truthy expect(dc.migrate_command).to eq('bar migrate') end it "return the false when migrate is false" do env = env_config('migrate' => false, 'migration_command' => 'bar migrate') dc = deploy_config({}, env) expect(dc.migrate).to be_falsey expect(dc.migrate_command).to be_nil end it "tells you to run ey init" do env = env_config('migrate' => true) dc = deploy_config({}, env) expect(dc.migrate).to be_truthy expect { dc.migrate_command }.to raise_error(EY::Error, /'migration_command' not found/) end it "return the ey.yml migration_command when command line option --migrate is passed" do env = env_config('migrate' => false, 'migration_command' => 'bar migrate') dc = deploy_config({'migrate' => true}, env) expect(dc.migrate).to be_truthy expect(dc.migrate_command).to eq('bar migrate') end end describe "ref" do it "returns the passed ref" do expect(deploy_config({'ref' => 'master'}).ref).to eq('master') end it "returns the passed force_ref" do expect(deploy_config({'force_ref' => 'force'}).ref).to eq('force') end it "returns the ref if force_ref is true" do expect(deploy_config({'ref' => 'master', 'force_ref' => true}).ref).to eq('master') end it "overrides the ref if force_ref is set to a string" do expect(deploy_config({'ref' => 'master', 'force_ref' => 'force'}).ref).to eq('force') end context "with a default branch" do let(:env) { env_config('branch' => 'default') } it "uses the configured default if ref is not passed" do out = capture_stdout do expect(deploy_config({}).ref).to eq('default') end expect(out).to match(/Using default branch "default" from ey.yml/) end it "raises if a default is set and --ref is passed on the cli (and they don't match)" do expect { deploy_config({'ref' => 'master'}).ref }.to raise_error(EY::BranchMismatchError) end it "returns the default if a default is set and --ref is the same" do expect(deploy_config({'ref' => 'default'}).ref).to eq('default') end it "returns the ref if force_ref is set" do out = capture_stdout do expect(deploy_config({'ref' => 'master', 'force_ref' => true}).ref).to eq('master') end expect(out).to match(/Default ref overridden with "master"/) end it "returns the ref if force_ref is a branch" do out = capture_stdout do expect(deploy_config({'force_ref' => 'master'}).ref).to eq('master') end expect(out).to match(/Default ref overridden with "master"/) end end context "no options, no default" do it "uses the repo's current branch" do expect(repo).to receive(:current_branch).and_return('current') out = capture_stdout do expect(deploy_config({}).ref).to eq('current') end expect(out).to match(/Using current HEAD branch "current"/) end end end end context "when outside of a repo" do describe "migrate" do it "returns the default migration command when migrate is true" do dc = deploy_config({'app' => 'app', 'migrate' => true}) expect(dc.migrate).to be_truthy expect(dc.migrate_command).to eq('rake db:migrate --trace') end it "returns false when nil" do dc = deploy_config({'app' => 'app', 'migrate' => nil}) expect(dc.migrate).to be_falsey expect(dc.migrate_command).to be_nil end it "return the custom migration command when is a string" do dc = deploy_config({'app' => 'app', 'migrate' => 'foo migrate'}) expect(dc.migrate).to be_truthy expect(dc.migrate_command).to eq('foo migrate') end it "raises if migrate is not passed" do expect { deploy_config({'app' => 'app'}).migrate }.to raise_error(EY::RefAndMigrateRequiredOutsideRepo) end end describe "ref" do it "returns the passed ref" do dc = deploy_config({'app' => 'app', 'ref' => 'master'}) expect(dc.ref).to eq('master') end it "returns the passed force_ref" do dc = deploy_config({'app' => 'app', 'force_ref' => 'force'}) expect(dc.ref).to eq('force') end it "returns the ref if force_ref is true" do dc = deploy_config({'app' => 'app', 'ref' => 'master', 'force_ref' => true}) expect(dc.ref).to eq('master') end it "overrides the ref if force_ref is set to a string" do dc = deploy_config({'app' => 'app', 'ref' => 'master', 'force_ref' => 'force'}) expect(dc.ref).to eq('force') end it "raises if ref is not passed" do expect { deploy_config({'app' => 'app'}).ref }.to raise_error(EY::RefAndMigrateRequiredOutsideRepo) end end end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/spec/engineyard/config_spec.rb
spec/engineyard/config_spec.rb
require 'spec_helper' require 'uri' describe EY::Config do describe "environments" do after { File.unlink('ey.yml') if File.exist?('ey.yml') } it "get loaded from the config file" do write_yaml({"environments" => {"production" => {"default" => true}}}, 'ey.yml') expect(EY::Config.new.environments["production"]["default"]).to be_truthy end it "are present when the config file has no environments key" do write_yaml({}, 'ey.yml') expect(EY::Config.new.environments).to eq({}) end it "rases an error when yaml produces an unexpected result" do File.open('ey.yml', "w") {|f| f << "this isn't a hash" } expect { EY::Config.new }.to raise_error(RuntimeError, "ey.yml load error: Expected a Hash but a String was returned.") end it "doesnt crash on nil environment" do write_yaml({"environments" => {"production" => nil}}, 'ey.yml') expect(EY::Config.new.default_environment).to be_nil end end describe "endpoint" do it "defaults to production Engine Yard Cloud" do expect(EY::Config.new.endpoint).to eq(EY::Config.new.default_endpoint) end it "loads the endpoint from $CLOUD_URL" do ENV['CLOUD_URL'] = "http://fake.local/" expect(EY::Config.new.endpoint).to eq('http://fake.local/') ENV.delete('CLOUD_URL') end end describe "files" do it "looks for config/ey.yml" do FileUtils.mkdir_p('config') write_yaml({"environments" => {"staging" => {"default" => true}}}, "ey.yml") write_yaml({"environments" => {"production" => {"default" => true}}}, "config/ey.yml") expect(EY::Config.new.default_environment).to eq("production") File.unlink('config/ey.yml') if File.exist?('config/ey.yml') File.unlink('ey.yml') if File.exist?('ey.yml') end it "looks for ey.yml" do write_yaml({"environments" => {"staging" => {"default" => true}}}, "ey.yml") expect(EY::Config.new.default_environment).to eq("staging") File.unlink('ey.yml') if File.exist?('ey.yml') end end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/spec/engineyard/cli/api_spec.rb
spec/engineyard/cli/api_spec.rb
require 'spec_helper' require 'engineyard/cli' describe EY::CLI::API do it "gets the api token from ~/.eyrc if possible" do write_eyrc({"api_token" => "asdf"}) expect(EY::CLI::API.new('http://fake.local', EY::CLI::UI.new).token).to eq("asdf") clean_eyrc end it "uses the token specified token over the ENV token if passed" do ENV['ENGINEYARD_API_TOKEN'] = 'envtoken' expect(EY::CLI::API.new('http://fake.local', EY::CLI::UI.new, 'specifiedtoken').token).to eq('specifiedtoken') ENV.delete('ENGINEYARD_API_TOKEN') end it "uses the token from $ENGINEYARD_API_TOKEN if set" do ENV['ENGINEYARD_API_TOKEN'] = 'envtoken' expect(EY::CLI::API.new('http://fake.local', EY::CLI::UI.new).token).to eq('envtoken') ENV.delete('ENGINEYARD_API_TOKEN') end context "without saved api token" do before(:each) do clean_eyrc FakeWeb.register_uri(:post, "http://fake.local/api/v2/authenticate", :body => %|{"api_token": "asdf"}|, :content_type => 'application/json') EY::CLI::UI::Prompter.enable_mock! EY::CLI::UI::Prompter.add_answer "my@email.example.com" EY::CLI::UI::Prompter.add_answer "secret" capture_stdout do @api = EY::CLI::API.new('http://fake.local', EY::CLI::UI.new) end end it "asks you for your credentials" do expect(EY::CLI::UI::Prompter.questions).to eq(["Email: ","Password: "]) end it "gets the api token" do expect(@api.token).to eq("asdf") end it "saves the api token to ~/.eyrc" do expect(read_eyrc).to eq({"api_token" => "asdf"}) end end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/spec/ey/rebuild_spec.rb
spec/ey/rebuild_spec.rb
require 'spec_helper' describe "ey rebuild" do given "integration" def command_to_run(opts) cmd = ["rebuild"] cmd << "--environment" << opts[:environment] if opts[:environment] cmd << "--account" << opts[:account] if opts[:account] cmd end def verify_ran(scenario) expect(@out).to match(/Updating instances on #{scenario[:account]} \/ #{scenario[:environment]}/) end include_examples "it takes an environment name and an account name" end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/spec/ey/list_environments_spec.rb
spec/ey/list_environments_spec.rb
require 'spec_helper' describe "ey environments" do given "integration" before { @succeeds_on_multiple_matches = true } def command_to_run(opts) cmd = ["environments"] cmd << "--environment" << opts[:environment] if opts[:environment] cmd << "--app" << opts[:app] if opts[:app] cmd << "--account" << opts[:account] if opts[:account] cmd end def verify_ran(scenario) expect(@out).to match(/#{scenario[:environment]}/) if scenario[:environment] expect(@out).to match(/#{scenario[:application]}/) if scenario[:application] end include_examples "it takes an environment name and an app name and an account name" context "with no apps" do before do login_scenario "empty" end it "suggests that you use environments --all" do fast_failing_ey %w[environments] expect(@err).to match(/Use ey environments --all to see all environments./) end end context "with apps" do before(:all) do login_scenario "one app, many environments" end it "lists the environments your app is in" do fast_ey %w[environments] expect(@out).to include('main/rails232app') expect(@out).to match(/giblets/) expect(@out).to match(/bakon/) end it "lists the environments with specified app" do fast_ey %w[environments --app rails232app] expect(@out).to include('main/rails232app') expect(@out).to match(/giblets/) expect(@out).to match(/bakon/) end it "finds no environments with gibberish app" do fast_failing_ey %w[environments --account main --app gibberish] expect(@err).to match(/Use ey environments --all to see all environments./) end it "finds no environments with gibberish account" do fast_failing_ey %w[environments --account gibberish --app rails232] expect(@err).to match(/Use ey environments --all to see all environments./) end it "lists the environments that the app is in" do fast_ey %w[environments --app rails232app] expect(@out).to include('main/rails232app') expect(@out).to match(/giblets/) expect(@out).to match(/bakon/) end it "lists the environments that the app is in" do fast_ey %w[environments --account main] expect(@out).to include('main/rails232app') expect(@out).to match(/giblets/) expect(@out).to match(/bakon/) end it "lists the environments matching --environment" do fast_ey %w[environments -e gib] expect(@out).to include('main/rails232app') expect(@out).to match(/giblets/) expect(@out).not_to match(/bakon/) end it "reports failure to find a git repo when not in one" do Dir.chdir(Dir.tmpdir) do fast_failing_ey %w[environments] expect(@err).to match(/fatal: Not a git repository \(or any of the parent directories\): .*#{Regexp.escape(Dir.tmpdir)}/) expect(@out).not_to match(/no application configured/) end end it "lists all environments that have apps with -A" do fast_ey %w[environments -A] expect(@out).to include("bakon") expect(@out).to include("giblets") end it "outputs simply with -s" do fast_ey %w[environments -s], :debug => false expect(@out.split(/\n/).sort).to eq(["bakon", "giblets"]) end it "outputs all environments (including ones with no apps) simply with -A and -s" do fast_ey %w[environments -A -s], :debug => false expect(@out.split(/\n/).sort).to eq(["bakon", "beef", "giblets"]) end end end describe "ey environments with an ambiguous git repo" do given "integration" include_examples "it has an ambiguous git repo" it "lists environments from all apps using the git repo" do fast_ey %w[environments] expect(@out).to include("giblets") expect(@out).to include("keycollector_production") end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/spec/ey/status_spec.rb
spec/ey/status_spec.rb
require 'spec_helper' describe "ey environments" do given "integration" before(:all) do login_scenario "one app, many environments" end it "tells you it's never been deployed" do fast_failing_ey %w[status -e giblets] expect(@err).to match(/Application rails232app has not been deployed on giblets./) end it "outputs the status of the deployment" do fast_ey %w[deploy -e giblets --ref HEAD --no-migrate] fast_ey %w[status -e giblets] expect(@out).to match(/Application:\s+rails232app/) expect(@out).to match(/Environment:\s+giblets/) expect(@out).to match(/Ref:\s+HEAD/) expect(@out).to match(/Resolved Ref:\s+resolved-HEAD/) expect(@out).to match(/Commit:\s+[a-f0-9]{40}/) expect(@out).to match(/Migrate:\s+false/) expect(@out).to match(/Deployed by:\s+One App Many Envs/) expect(@out).to match(/Started at:/) expect(@out).to match(/Finished at:/) expect(@out).to match(/Deployment was successful/) end it "quiets almost all of the output with --quiet" do fast_ey %w[deploy -e giblets --ref HEAD --no-migrate] fast_ey %w[status -e giblets -q] expect(@out).not_to match(/Application:\s+rails232app/) expect(@out).not_to match(/Environment:\s+giblets/) expect(@out).not_to match(/Ref:\s+HEAD/) expect(@out).not_to match(/Resolved Ref:\s+resolved-HEAD/) expect(@out).not_to match(/Commit:\s+[a-f0-9]{40}/) expect(@out).not_to match(/Migrate:\s+false/) expect(@out).not_to match(/Deployed by:\s+One App Many Envs/) expect(@out).not_to match(/Started at:/) expect(@out).not_to match(/Finished at:/) expect(@out).to match(/Deployment was successful/) end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/spec/ey/deploy_spec.rb
spec/ey/deploy_spec.rb
require 'spec_helper' describe "ey deploy without an eyrc file" do given "integration" it "prompts for authentication before continuing" do api_scenario "one app, one environment" ey(%w[deploy --no-migrate], :hide_err => true) do |input| input.puts(scenario_email) input.puts(scenario_password) end expect(@out).to include("We need to fetch your API token; please log in.") expect(@out).to include("Email:") expect(@out).to include("Password:") expect(@ssh_commands).not_to be_empty expect(read_eyrc).to eq({"api_token" => scenario_api_token}) end it "uses the token on the command line" do api_scenario "one app, one environment" ey(%w[deploy --no-migrate --api-token] + [scenario_api_token]) expect(@ssh_commands).not_to be_empty end end describe "ey deploy" do given "integration" def command_to_run(opts) cmd = ["deploy"] cmd << "--environment" << opts[:environment] if opts[:environment] cmd << "--app" << opts[:app] if opts[:app] cmd << "--account" << opts[:account] if opts[:account] cmd << "--ref" << opts[:ref] if opts[:ref] cmd << "--migrate" if opts[:migrate] cmd << opts[:migrate] if opts[:migrate].respond_to?(:to_str) cmd << "--no-migrate" if opts[:migrate] == nil cmd << "--verbose" if opts[:verbose] cmd end def verify_ran(scenario) expect(@out).to match(/Beginning deploy.../) expect(@out).to match(/Application:\s+#{scenario[:application]}/) expect(@out).to match(/Environment:\s+#{scenario[:environment]}/) expect(@out).to match(/deployment recorded/i) expect(@ssh_commands).to have_command_like(/engineyard-serverside.*deploy.*--app #{scenario[:application]}/) end # common behavior include_examples "it takes an environment name and an app name and an account name" include_examples "it invokes engineyard-serverside" end describe "ey deploy" do given "integration" context "without ssh keys (with ssh enabled)" do before do ENV.delete('NO_SSH') allow(Net::SSH).to receive(:start).and_raise(Net::SSH::AuthenticationFailed.new("no key")) end after do ENV['NO_SSH'] = 'true' end it "tells you that you need to add an appropriate ssh key (even with --quiet)" do login_scenario "one app, one environment" fast_failing_ey %w[deploy --no-migrate --quiet] expect(@err).to include("Authentication Failed") end end context "with invalid input" do it "complains when there is no app" do login_scenario "empty" fast_failing_ey ["deploy"] expect(@err).to include(%|No application found|) end it "complains when the specified environment does not contain the app" do login_scenario "one app, one environment, not linked" fast_failing_ey %w[deploy -e giblets -r master] expect(@err).to match(/Application "rails232app" and environment "giblets" are not associated./) end it "complains when environment is not specified and app is in >1 environment" do login_scenario "one app, many environments" fast_failing_ey %w[deploy --ref master --no-migrate] expect(@err).to match(/Multiple application environments possible/i) end it "complains when the app master is in a non-running state" do login_scenario "one app, one environment, app master red" fast_failing_ey %w[deploy --environment giblets --ref master --no-migrate] expect(@err).not_to match(/No running instances/i) expect(@err).to match(/running.*\(green\)/) end end context "migration command" do before(:each) do login_scenario "one app, one environment" end context "no ey.yml" do def clean_ey_yml File.unlink 'ey.yml' if File.exist?('ey.yml') FileUtils.rm_r 'config' if FileTest.exist?('config') end before { clean_ey_yml } after { clean_ey_yml } it "tells you to run ey init" do fast_failing_ey %w[deploy] expect(@err).to match(/ey init/) expect(@ssh_commands).to be_empty end it "tells you to run ey init" do fast_failing_ey %w[deploy --migrate] expect(@err).to match(/ey init/) expect(@ssh_commands).to be_empty end end it "can be disabled with --no-migrate" do fast_ey %w[deploy --no-migrate] expect(@ssh_commands.last).to match(/engineyard-serverside.*deploy/) expect(@ssh_commands.last).not_to match(/--migrate/) end it "runs the migrate command when one is given" do fast_ey ['deploy', '--migrate', 'thor fancy:migrate'] expect(@ssh_commands.last).to match(/--migrate 'thor fancy:migrate'/) end context "ey.yml migrate only" do before { write_yaml({"defaults" => {"migrate" => true}}, 'ey.yml') } after { File.unlink 'ey.yml' } it "tells you to run ey init" do fast_failing_ey %w[deploy] expect(@err).to match(/ey init/) end end context "ey.yml migration_command only" do before { write_yaml({"defaults" => {"migration_command" => "thor fancy:migrate"}}, 'ey.yml') } after { File.unlink 'ey.yml' } it "tells you to run ey init" do fast_failing_ey %w[deploy] expect(@err).to match(/ey init/) end end context "ey.yml with environment specific options overriding the defaults" do before do write_yaml({ "defaults" => { "migrate" => true, "migration_command" => "rake plain:migrate"}, "environments" => {"giblets" => { "migration_command" => 'thor fancy:migrate' }} }, 'ey.yml') end after { File.unlink 'ey.yml' } it "migrates with the custom command" do fast_ey %w[deploy] expect(@ssh_commands.last).to match(/--migrate 'thor fancy:migrate'/) end end context "disabled in ey.yml" do before { write_yaml({"defaults" => {"migrate" => false}}, 'ey.yml') } after { File.unlink 'ey.yml' } it "does not migrate by default" do fast_ey %w[deploy] expect(@ssh_commands.last).to match(/engineyard-serverside.*deploy/) expect(@ssh_commands.last).not_to match(/--migrate/) end it "can be turned back on with --migrate" do fast_ey ["deploy", "--migrate", "rake fancy:migrate"] expect(@ssh_commands.last).to match(/--migrate 'rake fancy:migrate'/) end it "tells you to initialize ey.yml when --migrate is specified with no value" do fast_failing_ey %w[deploy --migrate] expect(@err).to match(/ey init/) end end context "customized and disabled in ey.yml" do before { write_yaml({"defaults" => { "migrate" => false, "migration_command" => "thor fancy:migrate" }}, 'ey.yml') } after { File.unlink 'ey.yml' } it "does not migrate by default" do fast_ey %w[deploy] expect(@ssh_commands.last).not_to match(/--migrate/) end it "migrates with the custom command when --migrate is specified with no value" do fast_ey %w[deploy --migrate] expect(@ssh_commands.last).to match(/--migrate 'thor fancy:migrate'/) end end end context "the --framework-env option" do before(:each) do login_scenario "one app, one environment" end it "passes the framework environment" do fast_ey %w[deploy --no-migrate] expect(@ssh_commands.last).to match(/--framework-env production/) end end context "choosing something to deploy" do use_git_repo('deploy test') before(:all) do login_scenario "one app, one environment" end context "without a configured default branch" do it "defaults to the checked-out local branch" do fast_ey %w[deploy --no-migrate] expect(@ssh_commands.last).to match(/--ref resolved-current-branch/) end it "deploys another branch if given" do fast_ey %w[deploy --ref master --no-migrate] expect(@ssh_commands.last).to match(/--ref resolved-master/) end it "deploys a tag if given" do fast_ey %w[deploy --ref v1 --no-migrate] expect(@ssh_commands.last).to match(/--ref resolved-v1/) end it "allows using --branch to specify a branch" do fast_ey %w[deploy --branch master --no-migrate] expect(@ssh_commands.last).to match(/--ref resolved-master/) end it "allows using --tag to specify the tag" do fast_ey %w[deploy --tag v1 --no-migrate] expect(@ssh_commands.last).to match(/--ref resolved-v1/) end end context "with a configured default branch" do before(:each) do write_yaml({"environments" => {"giblets" => {"branch" => "master", "migrate" => false}}}, 'ey.yml') end after(:each) do File.unlink "ey.yml" end it "deploys the default branch by default" do fast_ey %w[deploy] expect(@ssh_commands.last).to match(/--ref resolved-master/) end it "complains about a non-default branch without --ignore-default-branch" do fast_failing_ey %w[deploy -r current-branch] expect(@err).to match(/default branch is set to "master"/) end it "deploys a non-default branch with --ignore-default-branch" do fast_ey %w[deploy -r current-branch --ignore-default-branch] expect(@ssh_commands.last).to match(/--ref resolved-current-branch/) end it "deploys a non-default branch with --R ref" do fast_ey %w[deploy -R current-branch] expect(@ssh_commands.last).to match(/--ref resolved-current-branch/) end end end context "when there is extra configuration" do before(:each) do write_yaml({"environments" => {"giblets" => {"migrate" => true, "migration_command" => "rake", "bert" => "ernie"}}}, 'ey.yml') end after(:each) do File.unlink("ey.yml") end it "no longer gets passed along to engineyard-serverside (since serverside will read it on its own)" do fast_ey %w[deploy --no-migrate] expect(@ssh_commands.last).not_to match(/"bert":"ernie"/) end end context "specifying an environment" do before(:all) do login_scenario "one app, many similarly-named environments" end it "lets you choose by complete name even if the complete name is ambiguous" do fast_ey %w[deploy --environment railsapp_staging --no-migrate] expect(@out).to match(/Beginning deploy.../) expect(@out).to match(/Ref:\s+master/) expect(@out).to match(/Environment:\s+railsapp_staging/) end end context "--config (--extra-deploy-hook-options)" do before(:all) do login_scenario "one app, one environment" end def config_options if @ssh_commands.last =~ /--config (.*?)(?: -|$)/ # the echo strips off the layer of shell escaping, leaving us # with pristine JSON MultiJson.load `echo #{$1}` end end it "passes --config to engineyard-serverside" do ey %w[deploy --config some:stuff more:crap --no-migrate] expect(config_options).not_to be_nil expect(config_options['some']).to eq('stuff') expect(config_options['more']).to eq('crap') end it "supports legacy --extra-deploy-hook-options" do ey %w[deploy --extra-deploy-hook-options some:stuff more:crap --no-migrate] expect(config_options).not_to be_nil expect(config_options['some']).to eq('stuff') expect(config_options['more']).to eq('crap') end context "when ey.yml is present" do before do write_yaml({"environments" => {"giblets" => {"beer" => "stout", "migrate" => true, "migration_command" => "rake"}}}, 'ey.yml') end after { File.unlink("ey.yml") } it "overrides what's in ey.yml" do fast_ey %w[deploy --config beer:esb] expect(config_options['beer']).to eq('esb') end end end context "specifying the application" do before(:all) do login_scenario "one app, one environment" end before(:each) do @_deploy_spec_start_dir = Dir.getwd Dir.chdir(File.expand_path("~")) end after(:each) do Dir.chdir(@_deploy_spec_start_dir) end it "allows you to specify an app when not in a directory" do fast_ey %w[deploy --app rails232app --ref master --migrate] expect(@ssh_commands.last).to match(/--app rails232app/) expect(@ssh_commands.last).to match(/--ref resolved-master/) expect(@ssh_commands.last).to match(/--migrate 'rake db:migrate --trace'/) end it "requires that you specify a ref when specifying the application" do Dir.chdir(File.expand_path("~")) do fast_failing_ey %w[deploy --app rails232app --no-migrate] expect(@err).to match(/you must also specify the --ref/) end end it "requires that you specify a migrate option when specifying the application" do Dir.chdir(File.expand_path("~")) do fast_failing_ey %w[deploy --app rails232app --ref master] expect(@err).to match(/you must also specify .* --migrate or --no-migrate/) end end end context "setting a specific serverside version" do use_git_repo("deploy test") before(:all) do login_scenario "one app, one environment" end it "should send the correct serverside version when specified" do fast_ey %w[deploy --no-migrate --serverside-version 1.6.4] deploy_command = @ssh_commands.find {|c| c =~ /engineyard-serverside.*deploy/ } expect(deploy_command).to match(/engineyard-serverside _1.6.4_ deploy/) end it "should send the default serverside version when unspecified" do fast_ey %w[deploy --no-migrate] deploy_command = @ssh_commands.find {|c| c =~ /engineyard-serverside.*deploy/ } expect(deploy_command).to match(/engineyard-serverside _#{EY::ENGINEYARD_SERVERSIDE_VERSION}_ deploy/) end end context "sending necessary information" do use_git_repo("deploy test") before(:all) do login_scenario "one app, one environment" fast_ey %w[deploy --no-migrate] @deploy_command = @ssh_commands.find {|c| c =~ /engineyard-serverside.*deploy/ } end it "passes along the repository URL to engineyard-serverside" do expect(@deploy_command).to match(/--git user@git.host:path\/to\/repo.git/) end it "passes along the web server stack to engineyard-serverside" do expect(@deploy_command).to match(/--stack nginx_mongrel/) end end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/spec/ey/console_spec.rb
spec/ey/console_spec.rb
require 'spec_helper' print_my_args_ssh = "#!/bin/sh\necho ssh $*" shared_examples_for "running ey console" do given "integration" def extra_ey_options {:prepend_to_path => {'ssh' => "#!/bin/sh\necho ssh $*"}} end def command_to_run(opts) cmd = ["console"] cmd << "--environment" << opts[:environment] if opts[:environment] cmd << "--quiet" if opts[:quiet] cmd end end describe "ey console" do include_examples "running ey console" it "complains if it has no app master" do login_scenario "one app, many environments" ey %w[console -e bakon], :expect_failure => true expect(@err).to match(/'bakon' does not have any matching instances/) end it "opens the console on the right server" do login_scenario "one app, one environment" ey command_to_run(:environment => 'giblets', :verbose => true) expect(@raw_ssh_commands.select do |command| command =~ /^ssh -t turkey@app_master_hostname.+ bash -lc '.+bundle exec rails console'$/ end).not_to be_empty expect(@raw_ssh_commands.select do |command| command =~ /^ssh -t turkey.+$/ end.count).to eq(1) end it "is quiet" do login_scenario "one app, one environment" ey command_to_run(:environment => 'giblets', :quiet => true) expect(@out).to match(/ssh.*-t turkey/) expect(@out).not_to match(/Loading application data/) end it "runs in bash by default" do login_scenario "one app, one environment" ey command_to_run(:environment => 'giblets', :quiet => true) expect(@out).to match(/ssh.*bash -lc '.+bundle/) end it "raises an error when there are no matching hosts" do login_scenario "one app, one environment, no instances" ey command_to_run(:environment => 'giblets', :quiet => true), :expect_failure => true end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/spec/ey/scp_spec.rb
spec/ey/scp_spec.rb
require 'spec_helper' shared_examples_for "running ey scp" do given "integration" def extra_ey_options {:prepend_to_path => {'scp' => "#!/bin/sh\necho scp $*"}} end end shared_examples_for "running ey scp for select role" do given "integration" def extra_ey_options {:prepend_to_path => {'scp' => "#!/bin/sh\necho scp $*"}} end def command_to_run(opts) cmd = ["scp", opts[:from], opts[:to]].compact + (@scp_flag || []) cmd << "--environment" << opts[:environment] if opts[:environment] cmd << "--quiet" if opts[:quiet] cmd end it "runs the command on the right servers" do login_scenario "one app, one environment" ey command_to_run(from: "from", to: "to", environment: 'giblets', verbose: true) @hosts.each do |host_prefix| expect(@raw_ssh_commands.grep(/^scp from turkey@#{host_prefix}.+:to$/)).not_to be_empty end expect(@raw_ssh_commands.grep(/^scp from turkey@.+:to$/).count).to eq(@hosts.count) end it "is quiet" do login_scenario "one app, one environment" ey command_to_run(from: "from", to: "to", environment: 'giblets', quiet: true) expect(@out).to match(/scp.*from.*to/) expect(@out).not_to match(/Loading application data/) end it "raises an error when there are no matching hosts" do login_scenario "one app, one environment, no instances" ey command_to_run({from: "from", to: "to", environment: 'giblets', verbose: true}), expect_failure: true end it "errors correctly when no file paths are specified" do login_scenario "one app, one environment" ey command_to_run({environment: 'giblets', verbose: true}), expect_failure: true ey command_to_run({from: "from", environment: 'giblets', verbose: true}), expect_failure: true end end describe "ey scp" do include_examples "running ey scp" before(:all) do login_scenario "one app, many environments" end it "complains if it has no app master" do ey %w[scp from to -e bakon], :expect_failure => true expect(@err).to match(/'bakon' does not have any matching instances/) end end describe "ey scp with an ambiguous git repo" do include_examples "running ey scp" def command_to_run(_) %w[scp from to] end include_examples "it requires an unambiguous git repo" end describe "ey scp" do include_examples "running ey scp" def command_to_run(opts) cmd = %w[scp HOST:from to] cmd << "--environment" << opts[:environment] if opts[:environment] cmd << "--account" << opts[:account] if opts[:account] cmd end def verify_ran(scenario) scp_target = scenario[:ssh_username] + '@' + scenario[:master_hostname] expect(@raw_ssh_commands).to eq(["scp #{scp_target}:from to"]) end include_examples "it takes an environment name and an account name" end describe "ey scp --all" do before do @scp_flag = %w[--all] @hosts = %w(app_hostname app_master_hostname util_fluffy_hostname util_rocky_hostname db_master_hostname db_slave_1_hostname db_slave_2_hostname) end include_examples "running ey scp" include_examples "running ey scp for select role" end describe "ey scp --app-servers" do before do @scp_flag = %w[--app-servers] @hosts = %w(app_hostname app_master_hostname) end include_examples "running ey scp" include_examples "running ey scp for select role" end describe "ey scp --db-master" do before do @scp_flag = %w[--db-master] @hosts = %w(db_master_hostname) end include_examples "running ey scp" include_examples "running ey scp for select role" end describe "ey scp --db-slaves" do before do @scp_flag = %w[--db-slaves] @hosts = %w(db_slave_1_hostname db_slave_2_hostname) end include_examples "running ey scp" include_examples "running ey scp for select role" end describe "ey scp --db-servers" do before do @scp_flag = %w[--db-servers] @hosts = %w(db_master_hostname db_slave_1_hostname db_slave_2_hostname) end include_examples "running ey scp" include_examples "running ey scp for select role" end describe "ey scp --utilities" do before do @scp_flag = %w[--utilities] @hosts = %w(util_fluffy_hostname util_rocky_hostname) end include_examples "running ey scp" include_examples "running ey scp for select role" end describe "ey scp --utilities fluffy" do before do @scp_flag = %w[--utilities fluffy] @hosts = %w(util_fluffy_hostname) end include_examples "running ey scp" include_examples "running ey scp for select role" end describe "ey scp --utilities fluffy rocky" do before do @scp_flag = %w[--utilities fluffy rocky] @hosts = %w(util_fluffy_hostname util_rocky_hostname) end include_examples "running ey scp" include_examples "running ey scp for select role" end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/spec/ey/rollback_spec.rb
spec/ey/rollback_spec.rb
require 'spec_helper' describe "ey rollback" do given "integration" def command_to_run(opts) cmd = ["rollback"] cmd << "-e" << opts[:environment] if opts[:environment] cmd << "-a" << opts[:app] if opts[:app] cmd << "-c" << opts[:account] if opts[:account] cmd << "--verbose" if opts[:verbose] cmd end def verify_ran(scenario) expect(@out).to match(/Rolling back.*#{scenario[:application]}.*#{scenario[:environment]}/) expect(@err).to eq('') expect(@ssh_commands.last).to match(/engineyard-serverside.*deploy rollback.*--app #{scenario[:application]}/) end include_examples "it takes an environment name and an app name and an account name" include_examples "it invokes engineyard-serverside" it "passes along the web server stack to engineyard-serverside" do login_scenario "one app, one environment" ey %w[rollback] expect(@ssh_commands.last).to match(/--stack nginx_mongrel/) end context "--config (--extra-deploy-hook-options)" do before(:all) do login_scenario "one app, one environment" end def config_options if @ssh_commands.last =~ /--config (.*?)(?: -|$)/ # the echo strips off the layer of shell escaping, leaving us # with pristine JSON MultiJson.load `echo #{$1}` end end it "passes --config to engineyard-serverside" do ey %w[rollback --config some:stuff more:crap] expect(config_options).not_to be_nil expect(config_options['some']).to eq('stuff') expect(config_options['more']).to eq('crap') expect(config_options['input_ref']).not_to be_nil expect(config_options['deployed_by']).not_to be_nil end it "supports legacy --extra-deploy-hook-options" do ey %w[rollback --extra-deploy-hook-options some:stuff more:crap] expect(config_options).not_to be_nil expect(config_options['some']).to eq('stuff') expect(config_options['more']).to eq('crap') end context "when ey.yml is present" do before do write_yaml({"environments" => {"giblets" => {"beer" => "stout"}}}, 'ey.yml') end after { File.unlink("ey.yml") } it "overrides what's in ey.yml" do ey %w[rollback --config beer:esb] expect(config_options['beer']).to eq('esb') end end end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/spec/ey/login_spec.rb
spec/ey/login_spec.rb
require 'spec_helper' describe "ey login" do given "integration" context "logged in" do before do login_scenario 'empty' end it "returns the logged in user name" do ey %w[login] expect(@out).to include("User Name (#{scenario_email})") end end context "not logged in" do it "prompts for authentication before outputting the logged in user" do api_scenario "empty" ey(%w[login], :hide_err => true) do |input| input.puts(scenario_email) input.puts(scenario_password) end expect(@out).to include("We need to fetch your API token; please log in.") expect(@out).to include("Email:") expect(@out).to include("Password:") expect(@out).to include("User Name (#{scenario_email})") end end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/spec/ey/servers_spec.rb
spec/ey/servers_spec.rb
require 'spec_helper' describe "ey servers" do given "integration" def command_to_run(opts) cmd = ["servers"] cmd << "--environment" << opts[:environment] if opts[:environment] cmd << "--account" << opts[:account] if opts[:account] cmd end def verify_ran(scenario) expect(@out).to match(/#{scenario[:environment]}/) if scenario[:environment] expect(@out).to match(/#{scenario[:account]}/) if scenario[:account] end include_examples "it takes an environment name and an account name" context "with no servers" do before do login_scenario "empty" end it "prints error when no application found" do fast_failing_ey %w[servers] expect(@err).to match(/No application found/) end end context "with 1 server" do before(:all) do login_scenario "one app, many environments" end it "lists the servers with specified env" do fast_ey %w[servers -e giblets] expect(@out).to match(/main \/ giblets/) expect(@out).to include('1 server ') end end context "with servers" do before(:all) do login_scenario "two accounts, two apps, two environments, ambiguous" end it "lists the servers with specified env" do fast_ey %w[servers -c main -e giblets] expect(@out).to include("# 7 servers on main / giblets") expect(@out).to include("app_master_hostname.compute-1.amazonaws.com \ti-ddbbdd92\tapp_master") expect(@out).to include("app_hostname.compute-1.amazonaws.com \ti-d2e3f1b9\tapp") expect(@out).to include("db_master_hostname.compute-1.amazonaws.com \ti-d4cdddbf\tdb_master") expect(@out).to include("db_slave_1_hostname.compute-1.amazonaws.com \ti-asdfasdfaj\tdb_slave \tSlave I") expect(@out).to include("db_slave_2_hostname.compute-1.amazonaws.com \ti-asdfasdfaj\tdb_slave") expect(@out).to include("util_fluffy_hostname.compute-1.amazonaws.com\ti-80e3f1eb\tutil \tfluffy") expect(@out).to include("util_rocky_hostname.compute-1.amazonaws.com \ti-80etf1eb\tutil \trocky") end it "lists the servers with specified env with users" do fast_ey %w[servers -c main -e giblets -u] expect(@out).to include("# 7 servers on main / giblets") expect(@out).to include("turkey@app_master_hostname.compute-1.amazonaws.com \ti-ddbbdd92\tapp_master") expect(@out).to include("turkey@app_hostname.compute-1.amazonaws.com \ti-d2e3f1b9\tapp") expect(@out).to include("turkey@db_master_hostname.compute-1.amazonaws.com \ti-d4cdddbf\tdb_master") expect(@out).to include("turkey@db_slave_1_hostname.compute-1.amazonaws.com \ti-asdfasdfaj\tdb_slave \tSlave I") expect(@out).to include("turkey@db_slave_2_hostname.compute-1.amazonaws.com \ti-asdfasdfaj\tdb_slave") expect(@out).to include("turkey@util_fluffy_hostname.compute-1.amazonaws.com\ti-80e3f1eb\tutil \tfluffy") expect(@out).to include("turkey@util_rocky_hostname.compute-1.amazonaws.com \ti-80etf1eb\tutil \trocky") end it "lists simple format servers" do fast_ey %w[servers -c main -e giblets -qs], :debug => false expect(@out.split(/\n/).map {|x| x.split(/\t/) }).to eq([ ['app_master_hostname.compute-1.amazonaws.com', 'i-ddbbdd92', 'app_master' ], ['app_hostname.compute-1.amazonaws.com', 'i-d2e3f1b9', 'app' ], ['db_master_hostname.compute-1.amazonaws.com', 'i-d4cdddbf', 'db_master' ], ['db_slave_1_hostname.compute-1.amazonaws.com', 'i-asdfasdfaj', 'db_slave', 'Slave I'], ['db_slave_2_hostname.compute-1.amazonaws.com', 'i-asdfasdfaj', 'db_slave' ], ['util_fluffy_hostname.compute-1.amazonaws.com', 'i-80e3f1eb', 'util', 'fluffy' ], ['util_rocky_hostname.compute-1.amazonaws.com', 'i-80etf1eb', 'util', 'rocky' ], ]) end it "lists simple format servers with users" do fast_ey %w[servers -c main -e giblets -qsu], :debug => false expect(@out.split(/\n/).map {|x| x.split(/\t/) }).to eq([ ['turkey@app_master_hostname.compute-1.amazonaws.com', 'i-ddbbdd92', 'app_master' ], ['turkey@app_hostname.compute-1.amazonaws.com', 'i-d2e3f1b9', 'app' ], ['turkey@db_master_hostname.compute-1.amazonaws.com', 'i-d4cdddbf', 'db_master' ], ['turkey@db_slave_1_hostname.compute-1.amazonaws.com', 'i-asdfasdfaj', 'db_slave', 'Slave I'], ['turkey@db_slave_2_hostname.compute-1.amazonaws.com', 'i-asdfasdfaj', 'db_slave' ], ['turkey@util_fluffy_hostname.compute-1.amazonaws.com', 'i-80e3f1eb', 'util', 'fluffy' ], ['turkey@util_rocky_hostname.compute-1.amazonaws.com', 'i-80etf1eb', 'util', 'rocky' ], ]) end it "lists host only" do fast_ey %w[servers -c main -e giblets -qS], :debug => false expect(@out.split(/\n/)).to eq([ 'app_master_hostname.compute-1.amazonaws.com', 'app_hostname.compute-1.amazonaws.com', 'db_master_hostname.compute-1.amazonaws.com', 'db_slave_1_hostname.compute-1.amazonaws.com', 'db_slave_2_hostname.compute-1.amazonaws.com', 'util_fluffy_hostname.compute-1.amazonaws.com', 'util_rocky_hostname.compute-1.amazonaws.com', ]) end it "lists host only with users" do fast_ey %w[servers -c main -e giblets -qSu], :debug => false expect(@out.split(/\n/)).to eq([ 'turkey@app_master_hostname.compute-1.amazonaws.com', 'turkey@app_hostname.compute-1.amazonaws.com', 'turkey@db_master_hostname.compute-1.amazonaws.com', 'turkey@db_slave_1_hostname.compute-1.amazonaws.com', 'turkey@db_slave_2_hostname.compute-1.amazonaws.com', 'turkey@util_fluffy_hostname.compute-1.amazonaws.com', 'turkey@util_rocky_hostname.compute-1.amazonaws.com', ]) end it "lists servers constrained to app servers" do fast_ey %w[servers -c main -e giblets -qs --app-servers], :debug => false expect(@out.split(/\n/).map {|x| x.split(/\t/) }).to eq([ ['app_master_hostname.compute-1.amazonaws.com', 'i-ddbbdd92', 'app_master' ], ['app_hostname.compute-1.amazonaws.com', 'i-d2e3f1b9', 'app' ], ]) end it "lists servers constrained to db servers" do fast_ey %w[servers -c main -e giblets -qs --db-servers], :debug => false expect(@out.split(/\n/).map {|x| x.split(/\t/) }).to eq([ ['db_master_hostname.compute-1.amazonaws.com', 'i-d4cdddbf', 'db_master' ], ['db_slave_1_hostname.compute-1.amazonaws.com', 'i-asdfasdfaj', 'db_slave', 'Slave I'], ['db_slave_2_hostname.compute-1.amazonaws.com', 'i-asdfasdfaj', 'db_slave' ], ]) end it "lists servers constrained to db master" do fast_ey %w[servers -c main -e giblets -qs --db-master], :debug => false expect(@out.split(/\n/).map {|x| x.split(/\t/) }).to eq([ ['db_master_hostname.compute-1.amazonaws.com', 'i-d4cdddbf', 'db_master' ], ]) end it "lists servers constrained to db slaves" do fast_ey %w[servers -c main -e giblets -qs --db-slaves], :debug => false expect(@out.split(/\n/).map {|x| x.split(/\t/) }).to eq([ ['db_slave_1_hostname.compute-1.amazonaws.com', 'i-asdfasdfaj', 'db_slave', 'Slave I'], ['db_slave_2_hostname.compute-1.amazonaws.com', 'i-asdfasdfaj', 'db_slave' ], ]) end it "lists servers constrained to utilities" do fast_ey %w[servers -c main -e giblets -qs --utilities], :debug => false expect(@out.split(/\n/).map {|x| x.split(/\t/) }).to eq([ ['util_fluffy_hostname.compute-1.amazonaws.com', 'i-80e3f1eb', 'util', 'fluffy' ], ['util_rocky_hostname.compute-1.amazonaws.com', 'i-80etf1eb', 'util', 'rocky' ], ]) end it "lists servers constrained to utilities with names" do fast_ey %w[servers -c main -e giblets -qs --utilities fluffy], :debug => false expect(@out.split(/\n/).map {|x| x.split(/\t/) }).to eq([ ['util_fluffy_hostname.compute-1.amazonaws.com', 'i-80e3f1eb', 'util', 'fluffy' ], ]) end it "lists servers constrained to app servers and utilities" do fast_ey %w[servers -c main -e giblets -qs --app --util], :debug => false expect(@out.split(/\n/).map {|x| x.split(/\t/) }).to eq([ ['app_master_hostname.compute-1.amazonaws.com', 'i-ddbbdd92', 'app_master' ], ['app_hostname.compute-1.amazonaws.com', 'i-d2e3f1b9', 'app' ], ['util_fluffy_hostname.compute-1.amazonaws.com', 'i-80e3f1eb', 'util', 'fluffy' ], ['util_rocky_hostname.compute-1.amazonaws.com', 'i-80etf1eb', 'util', 'rocky' ], ]) end it "lists servers constrained to app or util with name" do fast_ey %w[servers -c main -e giblets -qs --app --util rocky], :debug => false expect(@out.split(/\n/).map {|x| x.split(/\t/) }).to eq([ ['app_master_hostname.compute-1.amazonaws.com', 'i-ddbbdd92', 'app_master' ], ['app_hostname.compute-1.amazonaws.com', 'i-d2e3f1b9', 'app' ], ['util_rocky_hostname.compute-1.amazonaws.com', 'i-80etf1eb', 'util', 'rocky' ], ]) end it "finds no servers with gibberish " do fast_failing_ey %w[servers --account main --environment gibberish] expect(@err).to include('No environment found matching "gibberish"') end it "finds no servers with gibberish account" do fast_failing_ey %w[servers --account gibberish --environment giblets] expect(@err).to include('No account found matching "gibberish"') end it "reports failure to find a git repo when not in one" do Dir.chdir(Dir.tmpdir) do fast_failing_ey %w[servers] expect(@err).to match(/fatal: Not a git repository \(or any of the parent directories\): .*#{Regexp.escape(Dir.tmpdir)}/) expect(@out).not_to match(/no application configured/) end end end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/spec/ey/logout_spec.rb
spec/ey/logout_spec.rb
require 'spec_helper' describe "ey logout" do given "integration" context "logged in" do before { login_scenario 'empty' } it "logs you out" do ey %w[logout] expect(@out).to include("API token removed: #{ENV['EYRC']}") expect(@out).to include("Run any other command to login again.") end end context "not logged in" do it "doesn't prompt for login before logging out" do ey %w[logout] expect(@out).not_to include("API token removed:") expect(@out).to include("Already logged out.") expect(@out).to include("Run any other command to login again.") end end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/spec/ey/ssh_spec.rb
spec/ey/ssh_spec.rb
require 'spec_helper' print_my_args_ssh = "#!/bin/sh\necho ssh $*" shared_examples_for "running ey ssh" do given "integration" def extra_ey_options ssh_cmd = <<-RUBY #!#{`which ruby`} require "rubygems" require "escape" puts "ssh \#{Escape.shell_command(ARGV)}" RUBY {:prepend_to_path => {'ssh' => ssh_cmd}} end end shared_examples_for "running ey ssh for select role" do given "integration" def extra_ey_options {:prepend_to_path => {'ssh' => "#!/bin/sh\necho ssh $*"}} end def command_to_run(opts) cmd = ["ssh", opts[:ssh_command]].compact + (@ssh_flag || []) cmd << "--environment" << opts[:environment] if opts[:environment] cmd << "--shell" << opts[:shell] if opts[:shell] cmd << "--no-shell" if opts[:no_shell] cmd << "--quiet" if opts[:quiet] cmd end it "runs the command on the right servers" do login_scenario "one app, one environment" ey command_to_run(:ssh_command => "ls", :environment => 'giblets', :verbose => true) @hosts.each do |host| expect(@raw_ssh_commands.select do |command| command =~ /^ssh turkey@#{host}.+ ls$/ end).not_to be_empty end expect(@raw_ssh_commands.select do |command| command =~ /^ssh turkey.+ ls$/ end.count).to eq(@hosts.count) end it "is quiet" do login_scenario "one app, one environment" ey command_to_run(:ssh_command => "ls", :environment => 'giblets', :quiet => true) expect(@out).to match(/ssh.*ls/) expect(@out).not_to match(/Loading application data/) end it "runs in bash by default" do login_scenario "one app, one environment" ey command_to_run(:ssh_command => "ls", :environment => 'giblets') expect(@out).to match(/ssh.*bash -lc ls/) end it "excludes shell with --no-shell" do login_scenario "one app, one environment" ey command_to_run(:ssh_command => "ls", :environment => 'giblets', :no_shell => true) expect(@out).not_to match(/bash/) expect(@out).to match(/ssh.*ls/) end it "accepts an alternate shell" do login_scenario "one app, one environment" ey command_to_run(:ssh_command => "ls", :environment => 'giblets', :shell => 'zsh') expect(@out).to match(/ssh.*zsh -lc ls/) end it "raises an error when there are no matching hosts" do login_scenario "one app, one environment, no instances" ey command_to_run({:ssh_command => "ls", :environment => 'giblets', :verbose => true}), :expect_failure => true end it "responds correctly when there is no command" do if @hosts.count != 1 login_scenario "one app, one environment" ey command_to_run({:environment => 'giblets', :verbose => true}), :expect_failure => true end end end describe "ey ssh" do include_examples "running ey ssh" before(:all) do login_scenario "one app, many environments" end it "complains if it has no app master" do ey %w[ssh -e bakon], :expect_failure => true expect(@err).to match(/'bakon' does not have any matching instances/) end end describe "ey ssh with an ambiguous git repo" do include_examples "running ey ssh" def command_to_run(_) %w[ssh ls] end include_examples "it requires an unambiguous git repo" end describe "ey ssh without a command" do include_examples "running ey ssh" def command_to_run(opts) cmd = ["ssh"] cmd << "--environment" << opts[:environment] if opts[:environment] cmd << "--account" << opts[:account] if opts[:account] cmd end def verify_ran(scenario) ssh_target = scenario[:ssh_username] + '@' + scenario[:master_hostname] expect(@raw_ssh_commands).to eq(["ssh #{ssh_target}"]) end include_examples "it takes an environment name and an account name" end describe "ey ssh with a command" do include_examples "running ey ssh" def command_to_run(opts) cmd = %w[ssh ls] cmd << "--environment" << opts[:environment] if opts[:environment] cmd << "--account" << opts[:account] if opts[:account] cmd << "--shell" << opts[:shell] if opts[:shell] cmd << "--no-shell" if opts[:no_shell] cmd end def verify_ran(scenario) ssh_target = scenario[:ssh_username] + '@' + scenario[:master_hostname] expect(@raw_ssh_commands).to eq(["ssh #{ssh_target} 'bash -lc ls'"]) end include_examples "it takes an environment name and an account name" end describe "ey ssh with a command that fails" do given "integration" def extra_ey_options ssh_cmd = "false" # fail immediately {:prepend_to_path => {'ssh' => ssh_cmd}} end def command_to_run(opts) cmd = %w[ssh ls] cmd << "--environment" << opts[:environment] if opts[:environment] cmd << "--account" << opts[:account] if opts[:account] cmd << "--shell" << opts[:shell] if opts[:shell] cmd << "--no-shell" if opts[:no_shell] cmd end it "fails just like the ssh command fails" do login_scenario "one app, one environment" ey command_to_run({:ssh_command => "ls", :environment => 'giblets', :verbose => true}), :expect_failure => true end end describe "ey ssh with a multi-part command" do include_examples "running ey ssh" def command_to_run(opts) cmd = ['ssh', 'echo "echo"'] cmd << "--environment" << opts[:environment] if opts[:environment] cmd << "--account" << opts[:account] if opts[:account] cmd << "--shell" << opts[:shell] if opts[:shell] cmd << "--no-shell" if opts[:no_shell] cmd end def verify_ran(scenario) ssh_target = scenario[:ssh_username] + '@' + scenario[:master_hostname] expect(@raw_ssh_commands).to eq(["ssh #{ssh_target} 'bash -lc '\\''echo \"echo\"'\\'"]) end include_examples "it takes an environment name and an account name" end describe "ey ssh --all" do before do @ssh_flag = %w[--all] @hosts = %w(app_hostname app_master_hostname util_fluffy_hostname util_rocky_hostname db_master_hostname db_slave_1_hostname db_slave_2_hostname) end include_examples "running ey ssh" include_examples "running ey ssh for select role" end describe "ey ssh --app-servers" do before do @ssh_flag = %w[--app-servers] @hosts = %w(app_hostname app_master_hostname) end include_examples "running ey ssh" include_examples "running ey ssh for select role" end describe "ey ssh --db-master" do before do @ssh_flag = %w[--db-master] @hosts = %w(db_master_hostname) end include_examples "running ey ssh" include_examples "running ey ssh for select role" end describe "ey ssh --db-slaves" do before do @ssh_flag = %w[--db-slaves] @hosts = %w(db_slave_1_hostname db_slave_2_hostname) end include_examples "running ey ssh" include_examples "running ey ssh for select role" end describe "ey ssh --db-servers" do before do @ssh_flag = %w[--db-servers] @hosts = %w(db_master_hostname db_slave_1_hostname db_slave_2_hostname) end include_examples "running ey ssh" include_examples "running ey ssh for select role" end describe "ey ssh --utilities" do before do @ssh_flag = %w[--utilities] @hosts = %w(util_fluffy_hostname util_rocky_hostname) end include_examples "running ey ssh" include_examples "running ey ssh for select role" end describe "ey ssh --utilities fluffy" do before do @ssh_flag = %w[--utilities fluffy] @hosts = %w(util_fluffy_hostname) end include_examples "running ey ssh" include_examples "running ey ssh for select role" end describe "ey ssh --utilities fluffy rocky" do before do @ssh_flag = %w[--utilities fluffy rocky] @hosts = %w(util_fluffy_hostname util_rocky_hostname) end include_examples "running ey ssh" include_examples "running ey ssh for select role" end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/spec/ey/timeout_deploy_spec.rb
spec/ey/timeout_deploy_spec.rb
require 'spec_helper' describe "ey timeout-deploy" do given "integration" it "timeouts the last deployment" do login_scenario "Stuck Deployment" fast_ey %w[timeout-deploy] expect(@out).to match(/Marking last deployment failed.../) expect(@out).to match(/Finished at:\s+\w+/) end it "complains when there is no stuck deployment" do login_scenario "one app, one environment" fast_failing_ey ["timeout-deploy"] expect(@err).to include(%|No unfinished deployment was found for main / rails232app / giblets.|) end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/spec/ey/logs_spec.rb
spec/ey/logs_spec.rb
require 'spec_helper' describe "ey logs" do given "integration" it "prints logs returned by awsm" do login_scenario "one app, one environment" fast_ey %w[logs -e giblets] expect(@out).to match(/MAIN LOG OUTPUT/) expect(@out).to match(/CUSTOM LOG OUTPUT/) expect(@err).to eq('') end it "complains when it can't infer the environment" do login_scenario "one app, many environments" fast_failing_ey %w[logs] expect(@err).to match(/Multiple environments possible, please be more specific/i) end end describe "ey logs" do given "integration" def command_to_run(opts) cmd = ["logs"] cmd << "--environment" << opts[:environment] if opts[:environment] cmd << "--account" << opts[:account] if opts[:account] cmd end def verify_ran(scenario) expect(@out).to match(/Main logs for #{scenario[:environment]}/) end include_examples "it takes an environment name and an account name" end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/spec/ey/init_spec.rb
spec/ey/init_spec.rb
require 'spec_helper' describe "ey init" do given "integration" let(:default_migration_command) { "rake db:migrate --trace" } before do login_scenario "one app, one environment" end before { clean_ey_yml } after { clean_ey_yml } context "with no ey.yml file" do it "writes the file" do fast_ey %w[init] expect(ey_yml).to exist expect_config('migrate').to eq(false) end end context "with existing ey.yml file" do let(:existing) { { "defaults" => { "migrate" => false, "migration_command" => "thor fancy:migrate", "precompile_assets" => false, "precompile_assets_task" => "assets:precompile", }, "environments" => { "my_env" => { "default" => true, "migrate" => true, "migration_command" => default_migration_command, } } } } before do write_yaml(existing, 'ey.yml') end it "reinitializes the file" do fast_ey %w[init] expect_config('defaults','migration_command').to eq("thor fancy:migrate") expect_config('defaults','migrate').to eq(false) expect_config('defaults','precompile_assets').to eq(false) expect_config('environments','my_env','default').to eq(true) expect_config('environments','my_env','migrate').to eq(true) expect_config('environments','my_env','migration_command').to eq(default_migration_command) end it "makes a backup when overwriting an existing file" do fast_ey %w[init] data = read_yaml('ey.yml.backup') expect(data['defaults']['migration_command']).to eq('thor fancy:migrate') end end context "smart defaults" do describe "migrate" do let(:db) { Pathname.new('db') } let(:db_migrate) { db.join('migrate') } context "with db/migrate directory" do before { db_migrate.mkpath } after { db.rmtree } it "sets migrate to true and uses default migration command" do fast_ey %w[init] expect_config('migrate').to eq(true) expect_config('migration_command').to eq(default_migration_command) end end context "without db/migrate directory" do it "sets migrate to false and doesn't write migration_command" do expect(db_migrate).to_not exist fast_ey %w[init] expect_config('migrate').to eq(false) expect_config('migration_command').to be_nil end end end context "precompile_assets" do let(:app) { Pathname.new('app') } let(:assets) { app.join('assets') } context "with app/assets directory" do before { assets.mkpath } after { app.rmtree } it "sets precompile_assets to true and doesn't write precompile_assets_task" do fast_ey %w[init] expect_config('precompile_assets').to eq(true) expect_config('precompile_assets_task').to be_nil end end context "without app/assets directory" do it "sets precompile_assets to false and does not set an precompile_assets_task" do expect(assets).to_not exist fast_ey %w[init] expect_config('precompile_assets').to eq(false) expect_config('precompile_assets_task').to be_nil end end end end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/spec/ey/whoami_spec.rb
spec/ey/whoami_spec.rb
require 'spec_helper' describe "ey whoami" do given "integration" context "logged in" do before { login_scenario 'empty' } it "outputs the currently logged in user" do ey %w[whoami] expect(@out).to include("User Name (#{scenario_email})") end end context "not logged in" do it "prompts for authentication before outputting the logged in user" do api_scenario 'empty' ey(%w[whoami], :hide_err => true) do |input| input.puts(scenario_email) input.puts(scenario_password) end expect(@out).to include("We need to fetch your API token; please log in.") expect(@out).to include("Email:") expect(@out).to include("Password:") expect(@out).to include("User Name (#{scenario_email})") end end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/spec/ey/ey_spec.rb
spec/ey/ey_spec.rb
require 'spec_helper' describe "ey" do context "run without arguments" do it "prints usage information" do expect(ey).to include("Usage:") end end context "run with an argument that is not a command" do it "tells the user that is not a command" do ey %w[foobarbaz], :expect_failure => true expect(@err).to include("Could not find command") end end context "run a command and a bad flag" do it "tells the user that is not a valid flag" do ey %w[help --expect-failure], :expect_failure => true expect(@err).to include("Unknown switches") end end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/spec/ey/recipes/apply_spec.rb
spec/ey/recipes/apply_spec.rb
require 'spec_helper' describe "ey recipes apply" do given "integration" def command_to_run(opts) cmd = %w[recipes apply] cmd << "-e" << opts[:environment] if opts[:environment] cmd << "--account" << opts[:account] if opts[:account] cmd end def verify_ran(scenario) expect(@out).to match(/Uploaded recipes started for #{scenario[:environment]}/) end include_examples "it takes an environment name and an account name" it "fails when given a bad option" do fast_failing_ey %w[web enable --lots --of --bogus --options] expect(@err).to include("Unknown switches") end end describe "ey recipes apply with an ambiguous git repo" do given "integration" def command_to_run(_) %w[recipes apply] end include_examples "it requires an unambiguous git repo" end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/spec/ey/recipes/upload_spec.rb
spec/ey/recipes/upload_spec.rb
require 'spec_helper' describe "ey recipes upload" do given "integration" use_git_repo('+cookbooks') def command_to_run(opts) cmd = %w[recipes upload] cmd << "--environment" << opts[:environment] if opts[:environment] cmd << "--account" << opts[:account] if opts[:account] cmd end def verify_ran(scenario) expect(@out).to match(%r|Recipes in cookbooks/ uploaded successfully for #{scenario[:environment]}|) end include_examples "it takes an environment name and an account name" end describe "ey recipes upload -f recipes.tgz" do given "integration" use_git_repo('+recipes') def command_to_run(opts) cmd = %w[recipes upload] cmd << "--environment" << opts[:environment] if opts[:environment] cmd << "--account" << opts[:account] if opts[:account] cmd << "-f" << "recipes.tgz" cmd end def verify_ran(scenario) expect(@out).to match(%r|Recipes file recipes.tgz uploaded successfully for #{scenario[:environment]}|) end include_examples "it takes an environment name and an account name" end describe "ey recipes upload -f with a missing filenamen" do given "integration" def command_to_run(opts) cmd = %w[recipes upload] cmd << "--environment" << opts[:environment] if opts[:environment] cmd << "--account" << opts[:account] if opts[:account] cmd << "-f" << "recipes.tgz" cmd end it "errors with file not found" do login_scenario "one app, one environment" fast_failing_ey(%w[recipes upload --environment giblets -f recipes.tgz]) expect(@err).to match(/Recipes file not found: recipes.tgz/i) end end describe "ey recipes upload with an ambiguous git repo" do given "integration" def command_to_run(_) %w[recipes upload] end include_examples "it requires an unambiguous git repo" end describe "ey recipes upload from a separate cookbooks directory" do given "integration" context "without any git remotes" do use_git_repo "only cookbooks, no remotes" it "takes the environment specified by -e" do login_scenario "one app, one environment" ey %w[recipes upload -e giblets] expect(@out).to match(%r|Recipes in cookbooks/ uploaded successfully|) expect(@out).not_to match(/Uploaded recipes started for giblets/) end it "applies the recipes with --apply" do login_scenario "one app, one environment" ey %w[recipes upload -e giblets --apply] expect(@out).to match(%r|Recipes in cookbooks/ uploaded successfully|) expect(@out).to match(/Uploaded recipes started for giblets/) end end context "with a git remote unrelated to any application" do use_git_repo "only cookbooks, unrelated remotes" it "takes the environment specified by -e" do login_scenario "one app, one environment" ey %w[recipes upload -e giblets] expect(@out).to match(%r|Recipes in cookbooks/ uploaded successfully|) end end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/spec/ey/recipes/download_spec.rb
spec/ey/recipes/download_spec.rb
require 'spec_helper' describe "ey recipes download" do given "integration" use_git_repo('default') before(:each) do FileUtils.rm_rf('cookbooks') end after(:each) do # This test creates + destroys the cookbooks/ directory, thus # rendering the git repo unsuitable for reuse. EY.refresh_git_repo('default') end def command_to_run(opts) cmd = %w[recipes download] cmd << "--environment" << opts[:environment] if opts[:environment] cmd << "--account" << opts[:account] if opts[:account] cmd end def verify_ran(scenario) expect(@out).to match(/Recipes downloaded successfully for #{scenario[:environment]}/) expect(File.read('cookbooks/README')).to eq("Remove this file to clone an upstream git repository of cookbooks\n") end include_examples "it takes an environment name and an account name" it "fails when cookbooks/ already exists" do login_scenario "one app, one environment" Dir.mkdir("cookbooks") ey %w[recipes download], :expect_failure => true expect(@err).to match(/cookbooks.*already exists/i) end end describe "ey recipes download with an ambiguous git repo" do given "integration" def command_to_run(_) %w[recipes download] end include_examples "it requires an unambiguous git repo" end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/spec/ey/web/restart_spec.rb
spec/ey/web/restart_spec.rb
require 'spec_helper' describe "ey web restart" do given "integration" def command_to_run(opts) cmd = %w[web restart] cmd << "-e" << opts[:environment] if opts[:environment] cmd << "-a" << opts[:app] if opts[:app] cmd << "-c" << opts[:account] if opts[:account] cmd << "--verbose" if opts[:verbose] cmd end def verify_ran(scenario) expect(@ssh_commands).to have_command_like(/engineyard-serverside.*restart.*--app #{scenario[:application]}/) end include_examples "it takes an environment name and an app name and an account name" include_examples "it invokes engineyard-serverside" end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/spec/ey/web/enable_spec.rb
spec/ey/web/enable_spec.rb
require 'spec_helper' describe "ey web enable" do given "integration" def command_to_run(opts) cmd = %w[web enable] cmd << "-e" << opts[:environment] if opts[:environment] cmd << "-a" << opts[:app] if opts[:app] cmd << "-c" << opts[:account] if opts[:account] cmd << "--verbose" if opts[:verbose] cmd end def verify_ran(scenario) expect(@ssh_commands).to have_command_like(/engineyard-serverside.*disable_maintenance.*--app #{scenario[:application]}/) end include_examples "it takes an environment name and an app name and an account name" include_examples "it invokes engineyard-serverside" it "fails when given a bad option" do ey %w[web enable --lots --of --bogus --options], :expect_failure => true expect(@err).to include("Unknown switches") end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/spec/ey/web/disable_spec.rb
spec/ey/web/disable_spec.rb
require 'spec_helper' describe "ey web disable" do given "integration" def command_to_run(opts) cmd = %w[web disable] cmd << "-e" << opts[:environment] if opts[:environment] cmd << "-a" << opts[:app] if opts[:app] cmd << "-c" << opts[:account] if opts[:account] cmd << "--verbose" if opts[:verbose] cmd end def verify_ran(scenario) expect(@ssh_commands).to have_command_like(/engineyard-serverside.*enable_maintenance.*--app #{scenario[:application]}/) end include_examples "it takes an environment name and an app name and an account name" include_examples "it invokes engineyard-serverside" end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/lib/engineyard.rb
lib/engineyard.rb
module EY autoload :Repo, 'engineyard/repo' autoload :Templates, 'engineyard/templates' end require 'engineyard-cloud-client' require 'engineyard/version' require 'engineyard/error' require 'engineyard/config'
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/lib/vendor/thor/lib/thor.rb
lib/vendor/thor/lib/thor.rb
require 'set' require 'thor/base' class Thor class << self # Allows for custom "Command" package naming. # # === Parameters # name<String> # options<Hash> # def package_name(name, options={}) @package_name = name.nil? || name == '' ? nil : name end # Sets the default command when thor is executed without an explicit command to be called. # # ==== Parameters # meth<Symbol>:: name of the default command # def default_command(meth=nil) @default_command = case meth when :none 'help' when nil @default_command || from_superclass(:default_command, 'help') else meth.to_s end end alias default_task default_command # Registers another Thor subclass as a command. # # ==== Parameters # klass<Class>:: Thor subclass to register # command<String>:: Subcommand name to use # usage<String>:: Short usage for the subcommand # description<String>:: Description for the subcommand def register(klass, subcommand_name, usage, description, options={}) if klass <= Thor::Group desc usage, description, options define_method(subcommand_name) { |*args| invoke(klass, args) } else desc usage, description, options subcommand subcommand_name, klass end end # Defines the usage and the description of the next command. # # ==== Parameters # usage<String> # description<String> # options<String> # def desc(usage, description, options={}) if options[:for] command = find_and_refresh_command(options[:for]) command.usage = usage if usage command.description = description if description else @usage, @desc, @hide = usage, description, options[:hide] || false end end # Defines the long description of the next command. # # ==== Parameters # long description<String> # def long_desc(long_description, options={}) if options[:for] command = find_and_refresh_command(options[:for]) command.long_description = long_description if long_description else @long_desc = long_description end end # Maps an input to a command. If you define: # # map "-T" => "list" # # Running: # # thor -T # # Will invoke the list command. # # ==== Parameters # Hash[String|Array => Symbol]:: Maps the string or the strings in the array to the given command. # def map(mappings=nil) @map ||= from_superclass(:map, {}) if mappings mappings.each do |key, value| if key.respond_to?(:each) key.each {|subkey| @map[subkey] = value} else @map[key] = value end end end @map end # Declares the options for the next command to be declared. # # ==== Parameters # Hash[Symbol => Object]:: The hash key is the name of the option and the value # is the type of the option. Can be :string, :array, :hash, :boolean, :numeric # or :required (string). If you give a value, the type of the value is used. # def method_options(options=nil) @method_options ||= {} build_options(options, @method_options) if options @method_options end alias options method_options # Adds an option to the set of method options. If :for is given as option, # it allows you to change the options from a previous defined command. # # def previous_command # # magic # end # # method_option :foo => :bar, :for => :previous_command # # def next_command # # magic # end # # ==== Parameters # name<Symbol>:: The name of the argument. # options<Hash>:: Described below. # # ==== Options # :desc - Description for the argument. # :required - If the argument is required or not. # :default - Default value for this argument. It cannot be required and have default values. # :aliases - Aliases for this option. # :type - The type of the argument, can be :string, :hash, :array, :numeric or :boolean. # :banner - String to show on usage notes. # :hide - If you want to hide this option from the help. # def method_option(name, options={}) scope = if options[:for] find_and_refresh_command(options[:for]).options else method_options end build_option(name, options, scope) end alias option method_option # Prints help information for the given command. # # ==== Parameters # shell<Thor::Shell> # command_name<String> # def command_help(shell, command_name) meth = normalize_command_name(command_name) command = all_commands[meth] handle_no_command_error(meth) unless command shell.say "Usage:" shell.say " #{banner(command)}" shell.say class_options_help(shell, nil => command.options.map { |_, o| o }) if command.long_description shell.say "Description:" shell.print_wrapped(command.long_description, :indent => 2) else shell.say command.description end end alias task_help command_help # Prints help information for this class. # # ==== Parameters # shell<Thor::Shell> # def help(shell, subcommand = false) list = printable_commands(true, subcommand) Thor::Util.thor_classes_in(self).each do |klass| list += klass.printable_commands(false) end list.sort!{ |a,b| a[0] <=> b[0] } if @package_name shell.say "#{@package_name} commands:" else shell.say "Commands:" end shell.print_table(list, :indent => 2, :truncate => true) shell.say class_options_help(shell) end # Returns commands ready to be printed. def printable_commands(all = true, subcommand = false) (all ? all_commands : commands).map do |_, command| next if command.hidden? item = [] item << banner(command, false, subcommand) item << (command.description ? "# #{command.description.gsub(/\s+/m,' ')}" : "") item end.compact end alias printable_tasks printable_commands def subcommands @subcommands ||= from_superclass(:subcommands, []) end alias subtasks subcommands def subcommand(subcommand, subcommand_class) self.subcommands << subcommand.to_s subcommand_class.subcommand_help subcommand define_method(subcommand) do |*args| args, opts = Thor::Arguments.split(args) invoke subcommand_class, args, opts, :invoked_via_subcommand => true, :class_options => options end end alias subtask subcommand # Extend check unknown options to accept a hash of conditions. # # === Parameters # options<Hash>: A hash containing :only and/or :except keys def check_unknown_options!(options={}) @check_unknown_options ||= Hash.new options.each do |key, value| if value @check_unknown_options[key] = Array(value) else @check_unknown_options.delete(key) end end @check_unknown_options end # Overwrite check_unknown_options? to take subcommands and options into account. def check_unknown_options?(config) #:nodoc: options = check_unknown_options return false unless options command = config[:current_command] return true unless command name = command.name if subcommands.include?(name) false elsif options[:except] !options[:except].include?(name.to_sym) elsif options[:only] options[:only].include?(name.to_sym) else true end end # Stop parsing of options as soon as an unknown option or a regular # argument is encountered. All remaining arguments are passed to the command. # This is useful if you have a command that can receive arbitrary additional # options, and where those additional options should not be handled by # Thor. # # ==== Example # # To better understand how this is useful, let's consider a command that calls # an external command. A user may want to pass arbitrary options and # arguments to that command. The command itself also accepts some options, # which should be handled by Thor. # # class_option "verbose", :type => :boolean # stop_on_unknown_option! :exec # check_unknown_options! :except => :exec # # desc "exec", "Run a shell command" # def exec(*args) # puts "diagnostic output" if options[:verbose] # Kernel.exec(*args) # end # # Here +exec+ can be called with +--verbose+ to get diagnostic output, # e.g.: # # $ thor exec --verbose echo foo # diagnostic output # foo # # But if +--verbose+ is given after +echo+, it is passed to +echo+ instead: # # $ thor exec echo --verbose foo # --verbose foo # # ==== Parameters # Symbol ...:: A list of commands that should be affected. def stop_on_unknown_option!(*command_names) @stop_on_unknown_option ||= Set.new @stop_on_unknown_option.merge(command_names) end def stop_on_unknown_option?(command) #:nodoc: !!@stop_on_unknown_option && @stop_on_unknown_option.include?(command.name.to_sym) end protected # The method responsible for dispatching given the args. def dispatch(meth, given_args, given_opts, config) #:nodoc: # There is an edge case when dispatching from a subcommand. # A problem occurs invoking the default command. This case occurs # when arguments are passed and a default command is defined, and # the first given_args does not match the default command. # Thor use "help" by default so we skip that case. # Note the call to retrieve_command_name. It's called with # given_args.dup since that method calls args.shift. Then lookup # the command normally. If the first item in given_args is not # a command then use the default command. The given_args will be # intact later since dup was used. if config[:invoked_via_subcommand] && given_args.size >= 1 && default_command != "help" && given_args.first != default_command meth ||= retrieve_command_name(given_args.dup) command = all_commands[normalize_command_name(meth)] command ||= all_commands[normalize_command_name(default_command)] else meth ||= retrieve_command_name(given_args) command = all_commands[normalize_command_name(meth)] end if command args, opts = Thor::Options.split(given_args) if stop_on_unknown_option?(command) && !args.empty? # given_args starts with a non-option, so we treat everything as # ordinary arguments args.concat opts opts.clear end else args, opts = given_args, nil command = Thor::DynamicCommand.new(meth) end opts = given_opts || opts || [] config.merge!(:current_command => command, :command_options => command.options) instance = new(args, opts, config) yield instance if block_given? args = instance.args trailing = args[Range.new(arguments.size, -1)] instance.invoke_command(command, trailing || []) end # The banner for this class. You can customize it if you are invoking the # thor class by another ways which is not the Thor::Runner. It receives # the command that is going to be invoked and a boolean which indicates if # the namespace should be displayed as arguments. # def banner(command, namespace = nil, subcommand = false) "#{basename} #{command.formatted_usage(self, $thor_runner, subcommand)}" end def baseclass #:nodoc: Thor end def create_command(meth) #:nodoc: if @usage && @desc base_class = @hide ? Thor::HiddenCommand : Thor::Command commands[meth] = base_class.new(meth, @desc, @long_desc, @usage, method_options) @usage, @desc, @long_desc, @method_options, @hide = nil true elsif self.all_commands[meth] || meth == "method_missing" true else puts "[WARNING] Attempted to create command #{meth.inspect} without usage or description. " << "Call desc if you want this method to be available as command or declare it inside a " << "no_commands{} block. Invoked from #{caller[1].inspect}." false end end alias create_task create_command def initialize_added #:nodoc: class_options.merge!(method_options) @method_options = nil end # Retrieve the command name from given args. def retrieve_command_name(args) #:nodoc: meth = args.first.to_s unless args.empty? if meth && (map[meth] || meth !~ /^\-/) args.shift else nil end end alias retrieve_task_name retrieve_command_name # receives a (possibly nil) command name and returns a name that is in # the commands hash. In addition to normalizing aliases, this logic # will determine if a shortened command is an unambiguous substring of # a command or alias. # # +normalize_command_name+ also converts names like +animal-prison+ # into +animal_prison+. def normalize_command_name(meth) #:nodoc: return default_command.to_s.gsub('-', '_') unless meth possibilities = find_command_possibilities(meth) if possibilities.size > 1 raise ArgumentError, "Ambiguous command #{meth} matches [#{possibilities.join(', ')}]" elsif possibilities.size < 1 meth = meth || default_command elsif map[meth] meth = map[meth] else meth = possibilities.first end meth.to_s.gsub('-','_') # treat foo-bar as foo_bar end alias normalize_task_name normalize_command_name # this is the logic that takes the command name passed in by the user # and determines whether it is an unambiguous substrings of a command or # alias name. def find_command_possibilities(meth) len = meth.to_s.length possibilities = all_commands.merge(map).keys.select { |n| meth == n[0, len] }.sort unique_possibilities = possibilities.map { |k| map[k] || k }.uniq if possibilities.include?(meth) [meth] elsif unique_possibilities.size == 1 unique_possibilities else possibilities end end alias find_task_possibilities find_command_possibilities def subcommand_help(cmd) desc "help [COMMAND]", "Describe subcommands or one specific subcommand" class_eval <<-RUBY def help(command = nil, subcommand = true); super; end RUBY end alias subtask_help subcommand_help end include Thor::Base map HELP_MAPPINGS => :help desc "help [COMMAND]", "Describe available commands or one specific command" def help(command = nil, subcommand = false) command ? self.class.command_help(shell, command) : self.class.help(shell, subcommand) end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/lib/vendor/thor/lib/thor/command.rb
lib/vendor/thor/lib/thor/command.rb
class Thor class Command < Struct.new(:name, :description, :long_description, :usage, :options) FILE_REGEXP = /^#{Regexp.escape(File.dirname(__FILE__))}/ def initialize(name, description, long_description, usage, options=nil) super(name.to_s, description, long_description, usage, options || {}) end def initialize_copy(other) #:nodoc: super(other) self.options = other.options.dup if other.options end def hidden? false end # By default, a command invokes a method in the thor class. You can change this # implementation to create custom commands. def run(instance, args=[]) arity = nil if private_method?(instance) instance.class.handle_no_command_error(name) elsif public_method?(instance) arity = instance.method(name).arity instance.__send__(name, *args) elsif local_method?(instance, :method_missing) instance.__send__(:method_missing, name.to_sym, *args) else instance.class.handle_no_command_error(name) end rescue ArgumentError => e handle_argument_error?(instance, e, caller) ? instance.class.handle_argument_error(self, e, args, arity) : (raise e) rescue NoMethodError => e handle_no_method_error?(instance, e, caller) ? instance.class.handle_no_command_error(name) : (raise e) end # Returns the formatted usage by injecting given required arguments # and required options into the given usage. def formatted_usage(klass, namespace = true, subcommand = false) if namespace namespace = klass.namespace formatted = "#{namespace.gsub(/^(default)/,'')}:" end formatted = "#{klass.namespace.split(':').last} " if subcommand formatted ||= "" # Add usage with required arguments formatted << if klass && !klass.arguments.empty? usage.to_s.gsub(/^#{name}/) do |match| match << " " << klass.arguments.map{ |a| a.usage }.compact.join(' ') end else usage.to_s end # Add required options formatted << " #{required_options}" # Strip and go! formatted.strip end protected def not_debugging?(instance) !(instance.class.respond_to?(:debugging) && instance.class.debugging) end def required_options @required_options ||= options.map{ |_, o| o.usage if o.required? }.compact.sort.join(" ") end # Given a target, checks if this class name is a public method. def public_method?(instance) #:nodoc: !(instance.public_methods & [name.to_s, name.to_sym]).empty? end def private_method?(instance) !(instance.private_methods & [name.to_s, name.to_sym]).empty? end def local_method?(instance, name) methods = instance.public_methods(false) + instance.private_methods(false) + instance.protected_methods(false) !(methods & [name.to_s, name.to_sym]).empty? end def sans_backtrace(backtrace, caller) #:nodoc: saned = backtrace.reject { |frame| frame =~ FILE_REGEXP || (frame =~ /\.java:/ && RUBY_PLATFORM =~ /java/) } saned -= caller end def handle_argument_error?(instance, error, caller) not_debugging?(instance) && error.message =~ /wrong number of arguments/ && begin saned = sans_backtrace(error.backtrace, caller) # Ruby 1.9 always include the called method in the backtrace saned.empty? || (saned.size == 1 && RUBY_VERSION >= "1.9") end end def handle_no_method_error?(instance, error, caller) not_debugging?(instance) && error.message =~ /^undefined method `#{name}' for #{Regexp.escape(instance.to_s)}$/ end end Task = Command # A command that is hidden in help messages but still invocable. class HiddenCommand < Command def hidden? true end end HiddenTask = HiddenCommand # A dynamic command that handles method missing scenarios. class DynamicCommand < Command def initialize(name, options=nil) super(name.to_s, "A dynamically-generated command", name.to_s, name.to_s, options) end def run(instance, args=[]) if (instance.methods & [name.to_s, name.to_sym]).empty? super else instance.class.handle_no_command_error(name) end end end DynamicTask = DynamicCommand end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/lib/vendor/thor/lib/thor/actions.rb
lib/vendor/thor/lib/thor/actions.rb
require 'fileutils' require 'uri' require 'thor/core_ext/io_binary_read' require 'thor/actions/create_file' require 'thor/actions/create_link' require 'thor/actions/directory' require 'thor/actions/empty_directory' require 'thor/actions/file_manipulation' require 'thor/actions/inject_into_file' class Thor module Actions attr_accessor :behavior def self.included(base) #:nodoc: base.extend ClassMethods end module ClassMethods # Hold source paths for one Thor instance. source_paths_for_search is the # method responsible to gather source_paths from this current class, # inherited paths and the source root. # def source_paths @_source_paths ||= [] end # Stores and return the source root for this class def source_root(path=nil) @_source_root = path if path @_source_root end # Returns the source paths in the following order: # # 1) This class source paths # 2) Source root # 3) Parents source paths # def source_paths_for_search paths = [] paths += self.source_paths paths << self.source_root if self.source_root paths += from_superclass(:source_paths, []) paths end # Add runtime options that help actions execution. # def add_runtime_options! class_option :force, :type => :boolean, :aliases => "-f", :group => :runtime, :desc => "Overwrite files that already exist" class_option :pretend, :type => :boolean, :aliases => "-p", :group => :runtime, :desc => "Run but do not make any changes" class_option :quiet, :type => :boolean, :aliases => "-q", :group => :runtime, :desc => "Suppress status output" class_option :skip, :type => :boolean, :aliases => "-s", :group => :runtime, :desc => "Skip files that already exist" end end # Extends initializer to add more configuration options. # # ==== Configuration # behavior<Symbol>:: The actions default behavior. Can be :invoke or :revoke. # It also accepts :force, :skip and :pretend to set the behavior # and the respective option. # # destination_root<String>:: The root directory needed for some actions. # def initialize(args=[], options={}, config={}) self.behavior = case config[:behavior].to_s when "force", "skip" _cleanup_options_and_set(options, config[:behavior]) :invoke when "revoke" :revoke else :invoke end super self.destination_root = config[:destination_root] end # Wraps an action object and call it accordingly to the thor class behavior. # def action(instance) #:nodoc: if behavior == :revoke instance.revoke! else instance.invoke! end end # Returns the root for this thor class (also aliased as destination root). # def destination_root @destination_stack.last end # Sets the root for this thor class. Relatives path are added to the # directory where the script was invoked and expanded. # def destination_root=(root) @destination_stack ||= [] @destination_stack[0] = File.expand_path(root || '') end # Returns the given path relative to the absolute root (ie, root where # the script started). # def relative_to_original_destination_root(path, remove_dot=true) path = path.dup if path.gsub!(@destination_stack[0], '.') remove_dot ? (path[2..-1] || '') : path else path end end # Holds source paths in instance so they can be manipulated. # def source_paths @source_paths ||= self.class.source_paths_for_search end # Receives a file or directory and search for it in the source paths. # def find_in_source_paths(file) relative_root = relative_to_original_destination_root(destination_root, false) source_paths.each do |source| source_file = File.expand_path(file, File.join(source, relative_root)) return source_file if File.exists?(source_file) end message = "Could not find #{file.inspect} in any of your source paths. " unless self.class.source_root message << "Please invoke #{self.class.name}.source_root(PATH) with the PATH containing your templates. " end if source_paths.empty? message << "Currently you have no source paths." else message << "Your current source paths are: \n#{source_paths.join("\n")}" end raise Error, message end # Do something in the root or on a provided subfolder. If a relative path # is given it's referenced from the current root. The full path is yielded # to the block you provide. The path is set back to the previous path when # the method exits. # # ==== Parameters # dir<String>:: the directory to move to. # config<Hash>:: give :verbose => true to log and use padding. # def inside(dir='', config={}, &block) verbose = config.fetch(:verbose, false) pretend = options[:pretend] say_status :inside, dir, verbose shell.padding += 1 if verbose @destination_stack.push File.expand_path(dir, destination_root) # If the directory doesnt exist and we're not pretending if !File.exist?(destination_root) && !pretend FileUtils.mkdir_p(destination_root) end if pretend # In pretend mode, just yield down to the block block.arity == 1 ? yield(destination_root) : yield else FileUtils.cd(destination_root) { block.arity == 1 ? yield(destination_root) : yield } end @destination_stack.pop shell.padding -= 1 if verbose end # Goes to the root and execute the given block. # def in_root inside(@destination_stack.first) { yield } end # Loads an external file and execute it in the instance binding. # # ==== Parameters # path<String>:: The path to the file to execute. Can be a web address or # a relative path from the source root. # # ==== Examples # # apply "http://gist.github.com/103208" # # apply "recipes/jquery.rb" # def apply(path, config={}) verbose = config.fetch(:verbose, true) is_uri = path =~ /^https?\:\/\// path = find_in_source_paths(path) unless is_uri say_status :apply, path, verbose shell.padding += 1 if verbose if is_uri contents = open(path, "Accept" => "application/x-thor-template") {|io| io.read } else contents = open(path) {|io| io.read } end instance_eval(contents, path) shell.padding -= 1 if verbose end # Executes a command returning the contents of the command. # # ==== Parameters # command<String>:: the command to be executed. # config<Hash>:: give :verbose => false to not log the status, :capture => true to hide to output. Specify :with # to append an executable to command executation. # # ==== Example # # inside('vendor') do # run('ln -s ~/edge rails') # end # def run(command, config={}) return unless behavior == :invoke destination = relative_to_original_destination_root(destination_root, false) desc = "#{command} from #{destination.inspect}" if config[:with] desc = "#{File.basename(config[:with].to_s)} #{desc}" command = "#{config[:with]} #{command}" end say_status :run, desc, config.fetch(:verbose, true) unless options[:pretend] config[:capture] ? `#{command}` : system("#{command}") end end # Executes a ruby script (taking into account WIN32 platform quirks). # # ==== Parameters # command<String>:: the command to be executed. # config<Hash>:: give :verbose => false to not log the status. # def run_ruby_script(command, config={}) return unless behavior == :invoke run command, config.merge(:with => Thor::Util.ruby_command) end # Run a thor command. A hash of options can be given and it's converted to # switches. # # ==== Parameters # command<String>:: the command to be invoked # args<Array>:: arguments to the command # config<Hash>:: give :verbose => false to not log the status, :capture => true to hide to output. # Other options are given as parameter to Thor. # # # ==== Examples # # thor :install, "http://gist.github.com/103208" # #=> thor install http://gist.github.com/103208 # # thor :list, :all => true, :substring => 'rails' # #=> thor list --all --substring=rails # def thor(command, *args) config = args.last.is_a?(Hash) ? args.pop : {} verbose = config.key?(:verbose) ? config.delete(:verbose) : true pretend = config.key?(:pretend) ? config.delete(:pretend) : false capture = config.key?(:capture) ? config.delete(:capture) : false args.unshift(command) args.push Thor::Options.to_switches(config) command = args.join(' ').strip run command, :with => :thor, :verbose => verbose, :pretend => pretend, :capture => capture end protected # Allow current root to be shared between invocations. # def _shared_configuration #:nodoc: super.merge!(:destination_root => self.destination_root) end def _cleanup_options_and_set(options, key) #:nodoc: case options when Array %w(--force -f --skip -s).each { |i| options.delete(i) } options << "--#{key}" when Hash [:force, :skip, "force", "skip"].each { |i| options.delete(i) } options.merge!(key => true) end end end end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false
engineyard/engineyard
https://github.com/engineyard/engineyard/blob/14a6698100e5210692841dacae4457a0127d8a86/lib/vendor/thor/lib/thor/version.rb
lib/vendor/thor/lib/thor/version.rb
class Thor VERSION = "0.18.1" end
ruby
MIT
14a6698100e5210692841dacae4457a0127d8a86
2026-01-04T17:50:07.755432Z
false