github
Advanced Search
  • Home
  • Pricing and Signup
  • Explore GitHub
  • Blog
  • Login

drnic / rubigen

  • Admin
  • Watch Unwatch
  • Fork
  • Your Fork
  • Pull Request
  • Download Source
    • 46
    • 13
  • Source
  • Commits
  • Network (13)
  • Issues (0)
  • Downloads (9)
  • Wiki (1)
  • Graphs
  • Branch: master

click here to add a description

click here to add a homepage

  • Branches (3)
    • gh-pages
    • gsub_file
    • master ✓
  • Tags (9)
    • REL-1.5.2
    • REL-1.5.1
    • REL-1.5.0
    • REL-1.4.0
    • REL-1.3.4
    • REL-1.3.3
    • REL-1.3.2
    • REL-1.3.1
    • REL-1.3.0
Sending Request…
Enable Donations

Pledgie Donations

Once activated, we'll place the following badge in your repository's detail box:
Pledgie_example
This service is courtesy of Pledgie.

RubiGen - generator framework for your framework — Read more

  cancel

http://drnic.github.com/rubigen

  cancel
  • Private
  • Read-Only
  • HTTP Read-Only

This URL has Read+Write access

Merge branch 'master' of git://github.com/windock/rubigen 
drnic (author)
Mon Nov 09 01:05:30 -0800 2009
commit  76ebc1bccf2b0ebc4c04241124faefaa8470fef3
tree    7f416ef39ecb9f8c0f26e812e6f5c638ecb4ca07
parent  a312c8973b08282f60dc94b6903f876ed99e33fb parent  b8422db8ccb32bf5b83816ca6a22e6c5447d23d5
rubigen / lib / rubigen / lookup.rb lib/rubigen/lookup.rb
100644 306 lines (266 sloc) 10.194 kb
edit raw blame history
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
require File.dirname(__FILE__) + '/spec'
 
class Object
  class << self
    # Lookup missing generators using const_missing. This allows any
    # generator to reference another without having to know its location:
    # RubyGems, ~/.rubigen/generators, and APP_ROOT/generators.
    def lookup_missing_generator(class_id)
      if md = /(.+)Generator$/.match(class_id.to_s)
        name = md.captures.first.demodulize.underscore
        RubiGen::Base.active.lookup(name).klass
      else
        const_missing_before_generators(class_id)
      end
    end
 
    unless respond_to?(:const_missing_before_generators)
      alias_method :const_missing_before_generators, :const_missing
      alias_method :const_missing, :lookup_missing_generator
    end
  end
end
 
# User home directory lookup adapted from RubyGems.
def Dir.user_home
  if ENV['HOME']
    ENV['HOME']
  elsif ENV['USERPROFILE']
    ENV['USERPROFILE']
  elsif ENV['HOMEDRIVE'] and ENV['HOMEPATH']
    "#{ENV['HOMEDRIVE']}:#{ENV['HOMEPATH']}"
  else
    File.expand_path '~'
  end
end
 
 
module RubiGen
 
  # Generator lookup is managed by a list of sources which return specs
  # describing where to find and how to create generators. This module
  # provides class methods for manipulating the source list and looking up
  # generator specs, and an #instance wrapper for quickly instantiating
  # generators by name.
  #
  # A spec is not a generator: it's a description of where to find
  # the generator and how to create it. A source is anything that
  # yields generators from #each. PathSource and GemGeneratorSource are provided.
  module Lookup
    def self.included(base)
      base.extend(ClassMethods)
      # base.use_component_sources! # TODO is this required since it has no scope/source context
    end
 
    # Convenience method to instantiate another generator.
    def instance(generator_name, args, runtime_options = {})
      self.class.active.instance(generator_name, args, runtime_options)
    end
 
    module ClassMethods
      # The list of sources where we look, in order, for generators.
      def sources
        if read_inheritable_attribute(:sources).blank?
          if superclass == RubiGen::Base
            superclass_sources = superclass.sources
            diff = superclass_sources.inject([]) do |mem, source|
              found = false
              application_sources.each { |app_source| found ||= true if app_source == source}
              mem << source unless found
              mem
            end
            write_inheritable_attribute(:sources, diff)
          end
          active.use_component_sources! if read_inheritable_attribute(:sources).blank?
        end
        read_inheritable_attribute(:sources)
      end
 
      # Add a source to the end of the list.
      def append_sources(*args)
        sources.concat(args.flatten)
        invalidate_cache!
      end
 
      # Add a source to the beginning of the list.
      def prepend_sources(*args)
        sources = self.sources
        reset_sources
        write_inheritable_array(:sources, args.flatten + sources)
        invalidate_cache!
      end
 
      # Reset the source list.
      def reset_sources
        write_inheritable_attribute(:sources, [])
        invalidate_cache!
      end
      
      # Use application generators (app, ?).
      def use_application_sources!(*filters)
        reset_sources
        write_inheritable_attribute(:sources, application_sources(filters))
      end
      
      def application_sources(filters = [])
        filters.unshift 'app'
        app_sources = []
        app_sources << PathSource.new(:builtin, File.join(File.dirname(__FILE__), %w[.. .. app_generators]))
        app_sources << filtered_sources(filters)
        app_sources.flatten
      end
        
      # Use component generators (test_unit, etc).
      # 1. Current application. If APP_ROOT is defined we know we're
      # generating in the context of this application, so search
      # APP_ROOT/generators.
      # 2. User home directory. Search ~/.rubigen/generators.
      # 3. RubyGems. Search for gems containing /{scope}_generators folder.
      # 4. Builtins. None currently.
      #
      # Search can be filtered by passing one or more prefixes.
      # e.g. use_component_sources!(:rubygems) means it will also search in the following
      # folders:
      # 5. User home directory. Search ~/.rubigen/rubygems_generators.
      # 6. RubyGems. Search for gems containing /rubygems_generators folder.
      def use_component_sources!(*filters)
        reset_sources
        new_sources = []
        if defined? ::APP_ROOT
          new_sources << PathSource.new(:root, "#{::APP_ROOT}/generators")
          new_sources << PathSource.new(:vendor, "#{::APP_ROOT}/vendor/generators")
          new_sources << PathSource.new(:plugins, "#{::APP_ROOT}/vendor/plugins/*/**/generators")
        end
        new_sources << filtered_sources(filters)
        write_inheritable_attribute(:sources, new_sources.flatten)
      end
      
      def filtered_sources(filters)
        new_sources = []
        new_sources << PathFilteredSource.new(:user, "#{Dir.user_home}/.rubigen/", *filters)
        if Object.const_defined?(:Gem)
          new_sources << GemPathSource.new(*filters)
        end
        new_sources
      end
 
      # Lookup knows how to find generators' Specs from a list of Sources.
      # Searches the sources, in order, for the first matching name.
      def lookup(generator_name)
        @found ||= {}
        generator_name = generator_name.to_s.downcase
        @found[generator_name] ||= cache.find { |spec| spec.name == generator_name }
        unless @found[generator_name]
          chars = generator_name.scan(/./).map{|c|"#{c}.*?"}
          rx = /^#{chars}$/
          gns = cache.select {|spec| spec.name =~ rx }
          @found[generator_name] ||= gns.first if gns.length == 1
          raise GeneratorError, "Pattern '#{generator_name}' matches more than one generator: #{gns.map{|sp|sp.name}.join(', ')}" if gns.length > 1
        end
        @found[generator_name] or raise GeneratorError, "Couldn't find '#{generator_name}' generator"
      end
 
      # Convenience method to lookup and instantiate a generator.
      def instance(generator_name, args = [], runtime_options = {})
        active.lookup(generator_name).klass.new(args, full_options(runtime_options))
      end
 
      private
        # Lookup and cache every generator from the source list.
        def cache
          @cache ||= sources.inject([]) { |cache, source| cache + source.to_a }
        end
 
        # Clear the cache whenever the source list changes.
        def invalidate_cache!
          @cache = nil
        end
    end
  end
 
  # Sources enumerate (yield from #each) generator specs which describe
  # where to find and how to create generators. Enumerable is mixed in so,
  # for example, source.collect will retrieve every generator.
  # Sources may be assigned a label to distinguish them.
  class Source
    include Enumerable
 
    attr_reader :label
    def initialize(label)
      @label = label
    end
 
    # The each method must be implemented in subclasses.
    # The base implementation raises an error.
    def each
      raise NotImplementedError
    end
 
    # Return a convenient sorted list of all generator names.
    def names(filter = nil)
      inject([]) do |mem, spec|
        case filter
        when :visible
          mem << spec.name if spec.visible?
        end
        mem
      end.sort
    end
  end
 
 
  # PathSource looks for generators in a filesystem directory.
  class PathSource < Source
    attr_reader :path
 
    def initialize(label, path)
      super label
      @path = File.expand_path path
    end
 
    # Yield each eligible subdirectory.
    def each
      Dir["#{path}/[a-z]*"].each do |dir|
        if File.directory?(dir)
          yield Spec.new(File.basename(dir), dir, label)
        end
      end
    end
    
    def ==(source)
      self.class == source.class && path == source.path
    end
  end
  
  class PathFilteredSource < PathSource
    attr_reader :filters
    
    def initialize(label, path, *filters)
      super label, File.join(path, "#{filter_str(filters)}generators")
    end
    
    def filter_str(filters)
      @filters = filters.first.is_a?(Array) ? filters.first : filters
      return "" if @filters.blank?
      filter_str = @filters.map {|filter| "#{filter}_"}.join(",")
      filter_str += ","
      "{#{filter_str}}"
    end
 
    def ==(source)
      self.class == source.class && path == source.path && filters == source.filters && label == source.label
    end
  end
 
  class AbstractGemSource < Source
    def initialize
      super :RubyGems
    end
  end
 
  # GemPathSource looks for generators within any RubyGem's /{filter_}generators/**/<generator_name>_generator.rb file.
  class GemPathSource < AbstractGemSource
    attr_accessor :filters
    
    def initialize(*filters)
      super()
      @filters = filters
    end
    
    # Yield each generator within rails_generator subdirectories.
    def each
      generator_full_paths.each do |generator|
        yield Spec.new(File.basename(generator).sub(/_generator.rb$/, ''), File.dirname(generator), label)
      end
    end
 
    def ==(source)
      self.class == source.class && filters == source.filters
    end
 
    private
      def generator_full_paths
        @generator_full_paths ||=
          Gem::cache.inject({}) do |latest, name_gem|
            name, gem = name_gem
            hem = latest[gem.name]
            latest[gem.name] = gem if hem.nil? or gem.version > hem.version
            latest
          end.values.inject([]) do |mem, gem|
            Dir[gem.full_gem_path + "/#{filter_str}generators/**/*_generator.rb"].each do |generator|
              mem << generator
            end
            mem
          end.reverse
      end
      
      def filter_str
        @filters = filters.first.is_a?(Array) ? filters.first : filters
        return "" if filters.blank?
        filter_str = filters.map {|filter| "#{filter}_"}.join(",")
        filter_str += ","
        "{#{filter_str}}"
      end
  end
end
 
Blog | Support | Training | Contact | API | Status | Twitter | Help | Security
© 2010 GitHub Inc. All rights reserved. | Terms of Service | Privacy Policy
Powered by the Dedicated Servers and
Cloud Computing of Rackspace Hosting®
Dedicated Server