Skip to content

Commit

Permalink
Merge pull request #311 from hatsu38/add-column_names-method
Browse files Browse the repository at this point in the history
Add column names method
  • Loading branch information
kbrock authored Aug 21, 2024
2 parents f9ee4a4 + 9679a89 commit 627dc17
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 0 deletions.
17 changes: 17 additions & 0 deletions lib/active_hash/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,23 @@ def field_names
@field_names ||= []
end

#
# Useful for CSV integration needing column names as strings.
#
# @return [Array<String>] An array of column names as strings.
#
# @example Usage
# class Country < ActiveHash::Base
# fields :name, :code
# end
#
# Country.column_names
# # => ["id", "name", "code"]
#
def column_names
field_names.map(&:name)
end

def the_meta_class
class << self
self
Expand Down
11 changes: 11 additions & 0 deletions spec/active_hash/base_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,17 @@ class Country < ActiveHash::Base
end
end

describe ".column_names" do
before do
Country.fields :name, :iso_name, "size"
end

it "returns an array of column names" do
skip "Not supported in Ruby 3.0.0" if RUBY_VERSION < "3.0.0"
expect(Country.column_names).to eq(["name", "iso_name", "size"])
end
end

describe ".data=" do
before do
class Region < ActiveHash::Base
Expand Down
12 changes: 12 additions & 0 deletions spec/active_yaml/aliases_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,12 @@ class KeyProduct < ActiveYaml::Base
model.all
expect(model.field_names).to match_array [:name, :flavor, :price]
end

it 'excludes them from column_names' do
skip "Not supported in Ruby 3.0.0" if RUBY_VERSION < "3.0.0"
model.all
expect(model.column_names).to match_array ["name", "flavor", "price"]
end
end
end

Expand Down Expand Up @@ -70,6 +76,12 @@ class KeyProduct < ActiveYaml::Base
model.all
expect(model.field_names).to match_array [:name, :flavor, :price, :slogan, :key]
end

it 'excludes them from column_names' do
skip "Not supported in Ruby 3.0.0" if RUBY_VERSION < "3.0.0"
model.all
expect(model.column_names).to match_array ["name", "flavor", "price", "slogan", "key"]
end
end
end

Expand Down

0 comments on commit 627dc17

Please sign in to comment.