Looking for changes on website content https://projet-alice-demo.herokuapp.com/diffs/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

89 lines
1.5KB

  1. class Targets < ActiveRecord::Type::Value
  2. class Target
  3. def initialize(target)
  4. @from = target['from']
  5. @to = target['to']
  6. @css = target['css']
  7. end
  8. def extract_boundary(content)
  9. if @from
  10. i = content.index @from
  11. raise "Unable to find `from` #{@from}" unless i
  12. content = content[i..-1]
  13. end
  14. if @to
  15. i = content.index @to
  16. raise "Unable to find `to` #{@to}" unless i
  17. content = content[0..i]
  18. end
  19. content
  20. end
  21. def extract_css(content)
  22. return content unless @css
  23. content = Nokogiri::HTML.parse content
  24. node = content.at @css
  25. raise "Unable to find `css` #{@css}" unless node
  26. node.to_s
  27. end
  28. def extract(content)
  29. content = self.extract_boundary content
  30. content = self.extract_css content
  31. content
  32. end
  33. def to_h
  34. json = {}
  35. json['from'] = @from if @from
  36. json['to'] = @to if @to
  37. json['css'] = @css if @css
  38. json
  39. end
  40. def empty?
  41. !(@from || @to || @css)
  42. end
  43. end
  44. def self.detect(object)
  45. targets = object['targets']
  46. if targets
  47. targets = targets.collect { |t| create t }.flatten
  48. return nil if targets.empty?
  49. targets
  50. end
  51. target = create object
  52. return nil unless target
  53. [target]
  54. end
  55. def type
  56. :string
  57. end
  58. def deserialize(value)
  59. return nil unless value
  60. value = YAML.load value
  61. value.collect { |t| Target.new t }
  62. end
  63. def serialize(value)
  64. return nil unless value
  65. value = value.collect &:to_h
  66. YAML.dump value
  67. end
  68. private
  69. def self.create(target)
  70. target = Target.new target
  71. return nil if target.empty?
  72. target
  73. end
  74. end