diff --git a/README.md b/README.md index 204476c..b4cfbc4 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ working across different projects via [VisualMode](https://www.visualmode.dev/). For a steady stream of TILs, [sign up for my newsletter](https://visualmode.kit.com/newsletter). -_1734 TILs and counting..._ +_1735 TILs and counting..._ See some of the other learning resources I work on: @@ -1483,6 +1483,7 @@ If you've learned something here, support my efforts writing daily TILs by - [Single And Double Quoted String Notation](ruby/single-and-double-quoted-string-notation.md) - [Skip Specific CVEs When Auditing Your Bundle](ruby/skip-specific-cves-when-auditing-your-bundle.md) - [Skip The Front Of An Array With Drop](ruby/skip-the-front-of-an-array-with-drop.md) +- [Specify Default For Data Definition](ruby/specify-default-for-data-definition.md) - [Specify Dependencies For A Rake Task](ruby/specify-dependencies-for-a-rake-task.md) - [Specify How Random Array#sample Is](ruby/specify-how-random-array-sample-is.md) - [Split A Float Into Its Integer And Decimal](ruby/split-a-float-into-its-integer-and-decimal.md) diff --git a/ruby/specify-default-for-data-definition.md b/ruby/specify-default-for-data-definition.md new file mode 100644 index 0000000..0ba7109 --- /dev/null +++ b/ruby/specify-default-for-data-definition.md @@ -0,0 +1,43 @@ +# Specify Default For Data Definition + +Here is what a `Data` definition for the concept of a `Permission` might look +like: + +```ruby +Permission = Data.define(:id, :name, :description, :enabled) + +perm1 = Permission.new( + id: 123, + name: :can_edit, + description: "User is allowed to edit.", + enabled: true +) +``` + +However, as we're creating various `Permission` entities, we may find that the +vast majority of them are _enabled_ by default and so we'd like to apply `true` +as a default value. + +We cannot do this directly in the `Data` definition, but we can open a block to +override the `initialize` method. + +```ruby +Permission = Data.define(:id, :name, :description, :enabled) do + def initialize(:id, :name, :description, enabled: true) + super + end +end + +perm1 = Permission.new( + id: 123, + name: :can_edit, + description: "User is allowed to edit." +) + +perm1.enabled #=> true +``` + +Now we're able to create a `Permission` without specifying the `enabled` +attribute and it takes on the default of `true`. + +[source](https://dev.to/baweaver/new-in-ruby-32-datadefine-2819#comment-254o8)