Class: Modernize::Modernizer
- Inherits:
-
Object
- Object
- Modernize::Modernizer
- Defined in:
- lib/modernizer.rb
Instance Method Summary collapse
-
#initialize(&block) ⇒ Modernizer
constructor
Generates the set of migrations by parsing the passed in block.
-
#translate(context, hash) ⇒ Object
Translates a hash based on defined migrations with a given context and returns the hash.
Constructor Details
#initialize(&block) ⇒ Modernizer
Generates the set of migrations by parsing the passed in block
12 13 14 |
# File 'lib/modernizer.rb', line 12 def initialize(&block) @migrations = Parser.parse(&block) end |
Instance Method Details
#translate(context, hash) ⇒ Object
Translates a hash based on defined migrations with a given context and returns the hash. This will modify whatever gets passed in.
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
# File 'lib/modernizer.rb', line 20 def translate(context, hash) # makes sure that the context is a hash raise ArgumentError.new('did not pass a hash for the context') unless context.is_a?(Hash) raise ArgumentError.new('cannot provide include hash in context') if context[:hash] # create the context instance for instance variables struct = StructContext.new(context, hash) # instantiate MapMethods to perform translations and define lambda # for how to tranlate a field # translate = lambda { |t| MapMethods.send(t[:name], struct, t[:field], t[:block]) } # determine the version of the incoming hash # struct_version = struct.instance_exec(&@migrations.version) raise StandardError.new('calculated version is not valid') unless Gem::Version.correct?(struct_version) # gets a list of the potential versions # migration_versions = @migrations.translations.keys migration_versions.delete(:first) migration_versions.delete(:last) # get the first and last translations # firsts = @migrations.translations[:first] lasts = @migrations.translations[:last] # sorts the versions # migration_versions.sort! do |x,y| Gem::Version.new(x) <=> Gem::Version.new(y) end # reverse order if descending was specified # migration_versions = @migrations.order == :descending ? migration_versions.reverse : migration_versions # run the first translations if they exist # firsts.each(&translate) if firsts # determine the first version to run translations # first_index = @migrations.order == :ascending ? migration_versions.find_index(struct_version) : nil last_index = @migrations.order == :descending ? migration_versions.find_index(struct_version) : nil # run all subsequent version translations # migration_versions.each_with_index do |version, index| next unless !first_index || index >= first_index next unless !last_index || index <= last_index @migrations.translations[version].each(&translate) end # run the first translations if they exist # lasts.each(&translate) if lasts # return hash # struct.hash end |