Module: HumanID::Extension::Pattern
- Defined in:
- lib/humanid/extension/pattern.rb
Class Method Summary collapse
- .compile(handy_pattern) ⇒ Object
-
.guess(model_class) ⇒ Object
class CreateArticles < ActiveRecord::Migration def change create_table :articles do |t| t.string :name t.text :content end end end.
- .result(compiled_pattern, model) ⇒ Object
Class Method Details
.compile(handy_pattern) ⇒ Object
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 |
# File 'lib/humanid/extension/pattern.rb', line 8 def compile(handy_pattern) case handy_pattern # compile(['Article', :name]) # => [{string: 'Article'}, {method: :name}] when Array then handy_pattern # compile(:name) # => [{ method: :name }] when Symbol then [{ method: handy_pattern }] # compile(':id_:name') # => [ [{method: :id}, {string: '_'}, {method: :name}] ] # # compile('_:article_name:id_') # => [ [{string: '_'}, {method: :article_name}, {method: :id}, {string: '_'}] ] # # compile('article_:id') # => [ [{string: 'article_'}, {method: :id}] ] # # http://rubular.com/r/AJFnJbmBRo # # http://stackoverflow.com/questions/16398471/regex-not-ending-with # ?<! - not ending with else [handy_pattern.scan(/([\w-]+)|(:\w+(?<![_-]))/).flatten.compact.map do |el| el.start_with?(':') ? { method: el[1..-1].to_sym } : { string: el } end] end end |
.guess(model_class) ⇒ Object
class CreateArticles < ActiveRecord::Migration
def change
create_table :articles do |t|
t.string :name
t.text :content
end
end
end
class Article < ActiveRecord::Base end
guess(Article)
=> :name
52 53 54 55 56 |
# File 'lib/humanid/extension/pattern.rb', line 52 def guess(model_class) attrs = Traits.for(model_class).attributes attr = attrs.find { |el| el.string? } || attrs.find { |el| el.primary_key? } || attrs.first attr.name end |
.result(compiled_pattern, model) ⇒ Object
58 59 60 61 62 63 64 65 66 67 |
# File 'lib/humanid/extension/pattern.rb', line 58 def result(compiled_pattern, model) compiled_pattern.map do |el| case el when Symbol then model.send(el) when Hash then el.key?(:method) ? model.send(el[:method]) : el.fetch(:string) when Array then result(el, model).join('') else el end end end |