-
Notifications
You must be signed in to change notification settings - Fork 0
Quick Start
Leandro Segovia edited this page Feb 23, 2018
·
2 revisions
Imagine you have an xls
file like this:
To parse this file you need to:
class SuperheroesParser < Parxer::XlsParser
validate_file(:rows_count, max: 50) # Define file validators
column(:name, name: "Name") do # Map column names to attributes
validate(:presence) # Add column validator
format_with do
value.upcase # Define custom formatters
end
end
column(:real_name, name: "Real Name")
column(:super_power, name: "Super Power") do
validate(:presence)
end
column(:publisher, name: "Publisher") do
validate(:inclusion, in: ["Marvel", "DC"])
end
column(:age, name: "Alive") do
validate(:presence)
validate(:number)
format_with(:number, integer: true) # Use Parxer's formatter
end
column(:is_alive, name: "Alive", format: :boolean) do
validate(:presence)
end
# Define validators to run after attribute validators
validate_row(:odd_chars, if_valid: [:name, :real_name]) do
(row.name + row.real_name).delete(" ").size.odd?
end
# Define callbacks
after_parse_row do
row.add_attribute(:full_name) # Add attributes dynamically
row.full_name = "#{row.name} (#{row.real_name})" unless row.errors?
end
end
parser = SuperheroesParser.new
result = parser.run("/some_path/superhero.xls"); #=> #<Enumerator: ...>
Now, if you iterate through each row of the enumerator you will get something like this:
As you can see...
- Attributes like
name
oris_alive
have been formatted. - Errors in the rows are accessible through the
errors
attribute. -
idx
attribute is the row number. - the custom
full_name
attribute was added as a part of the response.