Skip to content

Instantly share code, notes, and snippets.

@myobie
Created January 16, 2009 15:59
Show Gist options
  • Save myobie/47976 to your computer and use it in GitHub Desktop.
Save myobie/47976 to your computer and use it in GitHub Desktop.
>> Review.detect?("Rating: 4\nItem: Dyson\n\nThis should be the description.")
=> true
>> Chat.detect?("You: Hello\nMe: Hello back at ya!\nYou: Wanna go eat\nYou: Somehwere\nMe: Yes!")
=> true
>> Chat.detect?("Rating: 4\nItem: Dyson\n\nThis should be the description.")
=> false
>> Review.detect?("You: Hello\nMe: Hello back at ya!\nYou: Wanna go eat\nYou: Somehwere\nMe: Yes!")
=> false
# The code that makes this work
# can be overriden to provide auto detection of type from a block of text
#
# Examples:
# def self.detect?(text)
# has_keys? text, :title, :body
# end
#
# def self.detect?(text)
# has_required? text
# end
#
# def self.detect?(text)
# has_one_or_more? text, :me
# end
#
def self.detect?(text)
false
end
# useful for detection
def self.has_keys?(text, *fields)
needed = fields.make_attrs
get_pairs_count(text, needed).length == needed.length
end
def self.has_more_than_one?(text, field)
has_more_than? text, field, 1
end
def self.has_one_or_more?(text, field)
has_more_than? text, field, 0
end
def self.has_more_than?(text, field, amount)
get_pairs_count(text, [field]).length > amount
end
def self.get_pairs(text)
TextImporter.new(self).import(text)
end
def self.get_pairs_count(text, fields)
pairs = get_pairs(text)
pairs.reject { |pair| !fields.include?(pair.keys.first) }
end
def self.has_required?(text)
has_keys? text, *self.required_fields_list
end
# runs through the list of children looking for one that will work
def self.auto_detect(text)
list = self.preferred_order.blank? ? @all_children : self.preferred_order
list.each { |l| return l.new(text) if l.detect?(text) }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment