Module: ActiveModel::Serializers::CSV
- Includes:
- ActiveModel::Serialization
- Defined in:
- lib/cloudxls-rails/activemodel.rb
Instance Method Summary collapse
-
#as_csv(options = nil) ⇒ Object
Returns an array representing the model.
Instance Method Details
#as_csv(options = nil) ⇒ Object
Returns an array representing the model. Some configuration can be passed through options
.
Without any options
, the returned Array will include all the model’s attributes.
user = User.find(1)
user.as_csv
# => [1, "Konata Izumi", 16, "2006-08-01", true]
The :only and :except options can be used to limit the attributes included, and work similar to the attributes
method.
user.as_csv(only: [:id, :name])
# => [1, "Konata Izumi"]
user.as_csv(except: [:id, :created_at, :age])
# => ["Konata Izumi", true]
To include the result of some method calls on the model use :methods:
user.as_csv(methods: :permalink)
# => [1, "Konata Izumi", 16, "2006-08-01", true, "1-konata-izumi"]
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
# File 'lib/cloudxls-rails/activemodel.rb', line 32 def as_csv( = nil) ||= {} attribute_names = attributes.keys if only = [:only] attribute_names = Array(only).map(&:to_s).select do |key| attribute_names.include?(key) end elsif except = [:except] attribute_names -= Array(except).map(&:to_s) end arr = [] attribute_names.each do |n| arr.push(read_attribute_for_serialization(n).as_csv) end Array([:methods]).each do |m| if respond_to?(m) val = send(m) if idx = attribute_names.index(m.to_s) arr[idx] = val else arr.push(val) end end end arr end |