Skip to content

Commit

Permalink
Document defining custom types
Browse files Browse the repository at this point in the history
  • Loading branch information
DmitryTsepelev committed Aug 9, 2019
1 parent 5e59d86 commit 5634038
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Expand Up @@ -89,6 +89,7 @@ product.save
* [Unknown attributes](./docs/unknown_attributes.md)
3. [Array of stored models](./docs/array_of_stored_models.md)
4. [Alternatives](./docs/alternatives.md)
5. [Defining custom types](./docs/defining_custom_types.md)

## License

Expand Down
46 changes: 46 additions & 0 deletions docs/defining_custom_types.md
@@ -0,0 +1,46 @@
Firstly, you should define your custom type (for instance, they can be kept inside the `app/types` directory):

```ruby
class Iso8601Type < ActiveRecord::Type::Value
def type
:datetime_iso8601
end

def cast(value)
return value if value.is_a?(Time)
return value.to_time if value.is_a?(Date)
return nil if value.blank?

Time.iso8601(value)
rescue ArgumentError, TypeError
nil
end
end

```

Secondly, register the type (initializer is a good place to do that):

```ruby
ActiveModel::Type.register(:datetime_iso8601, Iso8601Type)
```

Finally, use the type in your model:

```ruby
class Configuration
include StoreModel::Model

attribute :archived_at, :datetime_iso8601
end
```

Alternatively, you can skip registering the type globally in a following way:

```ruby
class Configuration
include StoreModel::Model

attribute :archived_at, Iso8601Type.new
end
```

0 comments on commit 5634038

Please sign in to comment.