Class: Eco::API::Common::People::EntryFactory

Inherits:
Session::BaseSession show all
Defined in:
lib/eco/api/common/people/entry_factory.rb

Overview

Helper factory class to generate entries (input entries).

Instance Attribute Summary collapse

Attributes inherited from Session::BaseSession

#api, #config, #environment, #file_manager, #logger, #session

Instance Method Summary collapse

Methods inherited from Session::BaseSession

#enviro=, #fm, #mailer, #mailer?, #s3uploader, #s3uploader?, #sftp, #sftp?

Constructor Details

#initialize(e, schema:, person_parser: nil, attr_map: nil) ⇒ EntryFactory

Returns a new instance of EntryFactory.

Parameters:

  • e (Eco::API::Common::Session::Environment)

    requires a session environment, as any child of Eco::API::Common::Session::BaseSession

  • schema (Ecoportal::API::V1::PersonSchema)

    schema of person details that the parser will be based upon.

  • person_parser (nil, Eco::API::Common::People::PersonParser) (defaults to: nil)

    set of attribute, type and format parsers/serializers.

  • attr_map (nil, Eco::Data::Mapper) (defaults to: nil)

    attribute names mapper to translate external names into internal ones and vice versa.



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/eco/api/common/people/entry_factory.rb', line 15

def initialize(e, schema:, person_parser: nil, attr_map: nil)
  fatal "Constructor needs a PersonSchema. Given: #{schema}" if !schema.is_a?(Ecoportal::API::V1::PersonSchema)
  fatal "Expecting PersonParser. Given: #{person_parser}"    if person_parser && !person_parser.is_a?(Eco::API::Common::People::PersonParser)
  fatal "Expecting Mapper object. Given: #{fields_mapper}"   if attr_map && !attr_map.is_a?(Eco::Data::Mapper)
  super(e)

  @schema = Ecoportal::API::V1::PersonSchema.new(JSON.parse(schema.doc.to_json))
  @source_person_parser = person_parser

  # load default parser + custom parsers
  base_parser = Eco::API::Common::People::DefaultParsers.new(schema: @schema).merge(@source_person_parser)
  # new parser with linked schema
  @person_parser = @source_person_parser.new(schema: @schema).merge(base_parser)
  @person_parser_patch_version = @source_person_parser.patch_version

  @attr_map = attr_map
end

Instance Attribute Details

#person_parserEco::API::Common::People::PersonParser (readonly)

Note:

if the custom person parser has changed, it updates the copy of this EntryFactory instance

provides with a Eco::API::Common::People::PersonParser object (collection of attribute parsers)

Returns:



36
37
38
# File 'lib/eco/api/common/people/entry_factory.rb', line 36

def person_parser
  @person_parser
end

#schemaEcoportal::API::V1::PersonSchema (readonly)

person schema to be used in this entry factory

Returns:

  • (Ecoportal::API::V1::PersonSchema)

    the current value of schema



7
8
9
# File 'lib/eco/api/common/people/entry_factory.rb', line 7

def schema
  @schema
end

Instance Method Details

#entries(data: (no_data = true; nil), file: (no_file = true; nil), format: (no_format = true; nil), encoding: nil) ⇒ Eco::API::Common::People::Entries

Helper that provides a collection of Entries, which in turn provides with further helpers to find and exclude entries. It accepts a file: and format: or data: but not both options together.

Parameters:

  • data (Array<Hash>) (defaults to: (no_data = true; nil))

    data to be parsed. It cannot be used alongside with file:

  • file (String) (defaults to: (no_file = true; nil))

    absolute or relative path to the input file. It cannot be used alongside with data:.

  • format (Symbol) (defaults to: (no_format = true; nil))

    it must be used when you use the option file: (i.e. :xml, :csv), as it specifies the format of the input file:.

  • encoding (String) (defaults to: nil)

    optional parameter to read file: by expecting certain encoding.

Returns:

Raises:

  • Exception

    • if you try to provide data: and file: at the same time.
    • if you provide file: but omit format:.
    • if the format: you provide is not a Symbol.
    • if there is no parser/serializer defined for format:.


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
# File 'lib/eco/api/common/people/entry_factory.rb', line 70

def entries(data: (no_data = true; nil), file: (no_file = true; nil), format: (no_format = true; nil), encoding: nil)
  fatal("You should at least use data: or file:, but not both") if no_data == no_file
  fatal("You must specify a valid format: (symbol) when you use file.") if file && no_format
  fatal("Format should be a Symbol. Given '#{format}'") if format && !format.is_a?(Symbol)
  fatal("There is no parser/serializer for format ':#{format.to_s}'") unless no_format || @person_parser.defined?(format)

  if file
    arr_hash = []
    if Eco::API::Common::Session::FileManager.file_exists?(file)
      encoding   ||= Eco::API::Common::Session::FileManager.encoding(file)
      encoding     = (encoding != "utf-8")? "#{encoding}|utf-8": encoding
      file_content = File.read(file, encoding: encoding)
      arr_hash     = person_parser.parse(format, file_content).map.each_with_index do |entry_hash, i|
        j = (format == :csv)? i + 2 : i + 1
        entry_hash.tap {|hash| hash["idx"] = j}
      end
    else
      logger.warn("File does not exist: #{file}")
    end

    entries(data: arr_hash)
  else
    Entries.new(data, klass: PersonEntry, factory: self)
  end
end

#export(data:, file: "export", format: :csv, encoding: "utf-8") ⇒ Void

Helper that generates a file out of data:.

Parameters:

  • data (Eco::API::Organization::People)

    data to be parsed.

  • file (String) (defaults to: "export")

    absolute or relative path to the ouput file.

  • format (Symbol) (defaults to: :csv)

    it specifies the format of the output file: (i.e. :xml, :csv). There must be a parser/serializer defined for it.

  • encoding (String) (defaults to: "utf-8")

    optional parameter to geneate file: content by unsing certain encoding.

Returns:

  • (Void)

    .

Raises:

  • Exception

    • if you try to provide data: in the wrong format.
    • if you file: is empty.
    • if the format: you provide is not a Symbol.
    • if there is no parser/serializer defined for format:.


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
# File 'lib/eco/api/common/people/entry_factory.rb', line 107

def export(data:, file: "export", format: :csv, encoding: "utf-8")
  fatal("data: Expected Eco::API::Organization::People object. Given: #{data.class}") unless data.is_a?(Eco::API::Organization::People)
  fatal("A file should be specified.") unless !file.to_s.strip.empty?
  fatal("Format should be a Symbol. Given '#{format}'") if format && !format.is_a?(Symbol)
  fatal("There is no parser/serializer for format ':#{format.to_s}'") unless @person_parser.defined?(format)

  run = true
  if Eco::API::Common::Session::FileManager.file_exists?(file)
    print "The file '#{file}' already exists. Do you want to overwrite it? (Y/n): "
    res = STDIN.gets.strip
    run = ["y", "Y", ""].include?(res)
  end

  if run
    deps = {"supervisor_id" => {people: data}}

    data_entries = data.map do |person|
      self.new(person, dependencies: deps).external_entry
    end

    File.open(file, "w", enconding: encoding) do |fd|
      fd.write(person_parser.serialize(format, data_entries))
    end
  end

end

#new(data, dependencies: {}) ⇒ Eco::API::Common::People::PersonEntry

Note:

this method is necessary to make the factory object work as a if it was a class PersonEntry you can call new on.

key method to generate objects of PersonEntry that share dependencies via this EntryFactory environment.

Parameters:

  • data (Array<Hash>)

    data to be parsed. The external hashed entry.

Returns:



48
49
50
51
52
53
54
55
56
# File 'lib/eco/api/common/people/entry_factory.rb', line 48

def new(data, dependencies: {})
  PersonEntry.new(
    data,
    person_parser: person_parser,
    attr_map:      @attr_map,
    dependencies:  dependencies,
    logger:        logger
  )
end