Skip to content

Commit

Permalink
Implement ignoring DSL to ignore attributes
Browse files Browse the repository at this point in the history
  • Loading branch information
okuramasafumi committed Aug 10, 2020
1 parent 05889f3 commit 358fb02
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 0 deletions.
30 changes: 30 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,36 @@ end

Although this might be useful sometimes, it's generally recommended to define a class for both Resource and Serializer.

### Inheritance and Ignorance

You can `exclude` or `ignore` certain attributes using `ignoring`.

```ruby
class Foo
attr_accessor :id, :name, :body

def initialize(id, name, body)
@id = id
@name = name
@body = body
end
end

class GenericFooResource
include Alba::Resource

attributes :id, :name, :body
end

class RestrictedFooResouce < GenericFooResource
ignoring :id, :body
end

RestrictedFooResouce.new(foo).serialize
# => '{"name":"my foo"}'
end
```

## Comparison

Alba is faster than alternatives.
Expand Down
7 changes: 7 additions & 0 deletions lib/alba/resource.rb
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,13 @@ def serializer(name)
def key(key)
@_key = key.to_sym
end

# Use this DSL in child class to ignore certain attributes
def ignoring(*attributes)
attributes.each do |attr_name|
@_attributes.delete(attr_name)
end
end
end
end
end
28 changes: 28 additions & 0 deletions test/usecases/inheritance_and_ignorance_test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
require_relative '../test_helper'

class InheritanceAndIgnoranceTest < MiniTest::Test
class Foo
attr_accessor :id, :name, :body

def initialize(id, name, body)
@id = id
@name = name
@body = body
end
end

class GenericFooResource
include Alba::Resource

attributes :id, :name, :body
end

class RestrictedFooResouce < GenericFooResource
ignoring :id, :body
end

def test_it_ignores_attributes
foo = Foo.new(1, 'my foo', 'my body')
assert_equal '{"name":"my foo"}', RestrictedFooResouce.new(foo).serialize
end
end

0 comments on commit 358fb02

Please sign in to comment.