base_resource.rb 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. module Import
  2. class BaseResource
  3. include Import::Helper
  4. def initialize(resource, *args)
  5. import(resource, *args)
  6. end
  7. def import_class
  8. raise "#{self.class.name} has no implmentation of the needed 'import_class' method"
  9. end
  10. def source
  11. raise "#{self.class.name} has no implmentation of the needed 'source' method"
  12. end
  13. def remote_id(resource, *_args)
  14. @remote_id ||= resource.delete(:id)
  15. end
  16. private
  17. def import(resource, *args)
  18. create_or_update(map(resource, *args), *args)
  19. end
  20. def create_or_update(resource, *args)
  21. return if updated?(resource, *args)
  22. create(resource, *args)
  23. end
  24. def updated?(resource, *args)
  25. @resource = lookup_existing(resource, *args)
  26. return false if !@resource
  27. @resource.update_attributes(resource)
  28. post_update(
  29. instance: @resource,
  30. attributes: resource
  31. )
  32. true
  33. end
  34. def lookup_existing(resource, *_args)
  35. instance = ExternalSync.find_by(
  36. source: source,
  37. source_id: remote_id(resource),
  38. object: import_class.name,
  39. )
  40. return if !instance
  41. import_class.find_by(id: instance.o_id)
  42. end
  43. def create(resource, *_args)
  44. @resource = import_class.new(resource)
  45. @resource.save
  46. ExternalSync.create(
  47. source: source,
  48. source_id: remote_id(resource),
  49. object: import_class.name,
  50. o_id: @resource.id
  51. )
  52. post_create(
  53. instance: @resource,
  54. attributes: resource
  55. )
  56. end
  57. def defaults(_resource, *_args)
  58. {
  59. created_by_id: 1,
  60. updated_by_id: 1,
  61. }
  62. end
  63. def map(resource, *args)
  64. mapped = from_mapping(resource, *args)
  65. attributes = defaults(resource, *args).merge(mapped)
  66. attributes.symbolize_keys
  67. end
  68. def from_mapping(resource, *args)
  69. return resource if !mapping(*args)
  70. ExternalSync.map(
  71. mapping: mapping,
  72. source: resource
  73. )
  74. end
  75. def mapping(*args)
  76. Setting.get(mapping_config(*args))
  77. end
  78. def mapping_config(*_args)
  79. self.class.name.to_s.sub('Import::', '').gsub('::', '_').underscore + '_mapping'
  80. end
  81. def post_create(_args)
  82. end
  83. def post_update(_args)
  84. end
  85. end
  86. end