Method: RDF::Format.for

Defined in:
lib/rdf/format.rb

.for(format) ⇒ Class .for(filename) ⇒ Class .for(options) ⇒ Class

Finds an RDF serialization format class based on the given criteria. If multiple formats are identified, the last one found is returned; this allows descrimination of equivalent formats based on load order.

Overloads:

  • .for(format) ⇒ Class

    Finds an RDF serialization format class based on a symbolic name.

    Parameters:

    • format (Symbol)

    Returns:

    • (Class)
  • .for(filename) ⇒ Class

    Finds an RDF serialization format class based on a file name.

    Parameters:

    Returns:

    • (Class)
  • .for(options) ⇒ Class

    Finds an RDF serialization format class based on various options.

    Content type may include wildcard characters, which will select among matching formats. Note that content_type will be taken from a URL opened using Util::File.open_file.

    Parameters:

    • options (Hash{Symbol => Object})

      ({})

    Options Hash (options):

    • :file_name (String, #to_s) — default: nil
    • :file_extension (Symbol, #to_sym) — default: nil
    • :content_type (String, #to_s) — default: nil
    • :has_reader (Boolean) — default: false

      Only return a format having a reader.

    • :has_writer (Boolean) — default: false

      Only return a format having a writer.

    • :sample (String) — default: nil

      A sample of input used for performing format detection. If we find no formats, or we find more than one, and we have a sample, we can perform format detection to find a specific format to use, in which case we pick the last one we find

    Yield Returns:

    • (String)

      another way to provide a sample, allows lazy for retrieving the sample.

    Returns:

    • (Class)

Returns:

  • (Class)


173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
# File 'lib/rdf/format.rb', line 173

def self.for(*arg, &block)
  case arg.length
  when 0 then arg = nil
  when 1 then arg = arg.first
  else
    raise ArgumentError, "Format.for accepts zero or one argument, got #{arg.length}."
  end

  options =  arg.is_a?(Hash) ? arg : {}
  options = {sample: block}.merge(options) if block_given?
  formats = case arg
  when String, RDF::URI
    # Find a format based on the file name
    self.each(file_name: arg, **options).to_a
  when Symbol
    # Try to find a match based on the full class name
    # We want this to work even if autoloading fails
    classes = self.each(**options).select {|f| f.symbols.include?(arg)}
    if classes.empty?
      classes = case arg
      when :ntriples then [RDF::NTriples::Format]
      when :nquads   then [RDF::NQuads::Format]
      else                []
      end
    end
    classes
  else
    self.each(**options.merge(all_if_none: false)).to_a
  end

  # Return the last detected format
  formats.last
end