{"id":28789892,"url":"https://github.com/public-law/validated_object","last_synced_at":"2025-11-11T19:28:07.897Z","repository":{"id":36642010,"uuid":"40948286","full_name":"public-law/validated_object","owner":"public-law","description":"Self-validating Ruby objects","archived":false,"fork":false,"pushed_at":"2025-06-12T00:56:35.000Z","size":196,"stargazers_count":64,"open_issues_count":2,"forks_count":2,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-06-17T10:59:38.827Z","etag":null,"topics":["activemodel","gem","rails-validations","ruby","strongly-typed"],"latest_commit_sha":null,"homepage":"https://rubygems.org/gems/validated_object","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/public-law.png","metadata":{"files":{"readme":"README.md","changelog":"HISTORY.md","contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2015-08-18T03:18:46.000Z","updated_at":"2025-06-13T05:38:59.000Z","dependencies_parsed_at":"2024-05-02T16:06:32.929Z","dependency_job_id":null,"html_url":"https://github.com/public-law/validated_object","commit_stats":null,"previous_names":["public-law/validated_object"],"tags_count":11,"template":false,"template_full_name":null,"purl":"pkg:github/public-law/validated_object","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/public-law%2Fvalidated_object","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/public-law%2Fvalidated_object/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/public-law%2Fvalidated_object/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/public-law%2Fvalidated_object/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/public-law","download_url":"https://codeload.github.com/public-law/validated_object/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/public-law%2Fvalidated_object/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":260346742,"owners_count":22995135,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["activemodel","gem","rails-validations","ruby","strongly-typed"],"created_at":"2025-06-17T22:30:38.169Z","updated_at":"2025-11-11T19:28:07.891Z","avatar_url":"https://github.com/public-law.png","language":"Ruby","readme":"[![Gem Version](https://badge.fury.io/rb/validated_object.svg)](https://badge.fury.io/rb/validated_object) \n# ValidatedObject\n\n**Self-validating Plain Old Ruby Objects** using Rails validations.\n\nCreate Ruby objects that validate themselves on instantiation, with clear error messages and flexible type checking including union types.\n\nResult: Invalid objects can't be instantiated. Illegal states are unrepresentable.\n\n```ruby\nclass Person \u003c ValidatedObject::Base\n  validates_attr :name, presence: true\n  validates_attr :email, format: { with: URI::MailTo::EMAIL_REGEXP }\nend\n\nPerson.new(name: 'Alice', email: 'alice@example.com')  # ✓ Valid\nPerson.new(name: '', email: 'invalid')  # ✗ ArgumentError: \"Name can't be blank; Email is invalid\"\n```\n\n## Key Features\n\n* **Union Types**: `union(String, Integer)` for flexible type validation\n* **Array Element Validation**: `type: [String]` ensures arrays contain specific types  \n* **Clear Error Messages**: Descriptive validation failures for debugging\n* **Rails Validations**: Full ActiveModel::Validations support\n* **Immutable Objects**: Read-only attributes with validation\n\nPerfect for data imports, API boundaries, and structured data generation.\n\n## Basic Usage\n\n### Simple Validation\n\n```ruby\nclass Dog \u003c ValidatedObject::Base\n  validates_attr :name, presence: true\n  validates_attr :age, type: Integer, allow_nil: true\nend\n\nspot = Dog.new(name: 'Spot', age: 3)\nspot.valid? # =\u003e true\n```\n\n### Type Validation\n\n```ruby\nclass Document \u003c ValidatedObject::Base\n  validates_attr :title, type: String\n  validates_attr :published_at, type: Date, allow_nil: true\n  validates_attr :active, type: Boolean\nend\n```\n\nThe `Boolean` type accepts `true` or `false` values.\n\n## Union Types\n\nUnion types allow attributes to accept multiple possible types:\n\n### Basic Union Types\n\n```ruby\nclass Article \u003c ValidatedObject::Base\n  # ID can be either a String or Integer\n  validates_attr :id, type: union(String, Integer)\n  \n  # Status can be specific symbol values\n  validates_attr :status, type: union(:draft, :published, :archived)\nend\n\narticle = Article.new(id: \"abc123\", status: :published)  # ✓ String ID\narticle = Article.new(id: 42, status: :draft)            # ✓ Integer ID\nArticle.new(id: 3.14, status: :invalid)                  # ✗ ArgumentError\n```\n\n### Mixed Type and Array Unions\n\n```ruby\nclass Post \u003c ValidatedObject::Base\n  # Author can be a Person object or Organization object\n  validates_attr :author, type: union(Person, Organization)\n  \n  # Tags can be a single string or array of strings\n  validates_attr :tags, type: union(String, [String])\n  \n  # Categories supports multiple formats\n  validates_attr :categories, type: union(String, [String], [Category])\nend\n\n# All of these are valid:\nPost.new(author: person, tags: \"ruby\")\nPost.new(author: org, tags: [\"ruby\", \"rails\"])  \nPost.new(author: person, categories: [category1, category2])\n```\n\n### Schema.org Example\n\nUnion types are perfect for Schema.org structured data:\n\n```ruby\nclass Organization \u003c ValidatedObject::Base\n  # Address can be text or structured PostalAddress\n  validates_attr :address, type: union(String, PostalAddress)\n  \n  # Founder can be Person or Organization\n  validates_attr :founder, type: union(Person, Organization, [Person], [Organization])\n  \n  # Logo can be URL string or ImageObject  \n  validates_attr :logo, type: union(String, ImageObject)\nend\n```\n\n## Array Element Validation\n\nValidate that arrays contain specific types:\n\n```ruby\nclass Playlist \u003c ValidatedObject::Base\n  validates_attr :songs, type: [Song]           # Array of Song objects\n  validates_attr :genres, type: [String]        # Array of strings\n  validates_attr :ratings, type: [Integer]      # Array of integers\nend\n\nplaylist = Playlist.new(\n  songs: [song1, song2],\n  genres: [\"rock\", \"jazz\"],  \n  ratings: [4, 5, 3]\n)\n```\n\n## Alternative Syntax\n\nYou can also use the standard Rails `validates` method:\n\n```ruby\nclass Dog \u003c ValidatedObject::Base\n  attr_reader :name, :birthday\n\n  validates :name, presence: true\n  validates :birthday, type: union(Date, DateTime), allow_nil: true\nend\n```\n\n## Error Messages\n\nValidatedObject provides clear, actionable error messages:\n\n```ruby\ndoc = Document.new(title: 123, status: :invalid)\n# =\u003e ArgumentError: Title is a Integer, not a String; Status is a Symbol, not one of :draft, :published, :archived\n\npost = Post.new(tags: [123, \"valid\"])  \n# =\u003e ArgumentError: Tags is a Array, not one of String, Array of String\n```\n\n## Use Cases\n\n### Data Import Validation\n\n```ruby\n# Import CSV with validation\nvalid_records = []\nCSV.foreach('data.csv', headers: true) do |row|\n  begin\n    valid_records \u003c\u003c Person.new(row.to_h)\n  rescue ArgumentError =\u003e e\n    logger.warn \"Invalid row: #{e.message}\"\n  end\nend\n```\n\n### API Response Objects\n\n```ruby\nclass ApiResponse \u003c ValidatedObject::Base\n  validates_attr :data, type: union(Hash, [Hash])\n  validates_attr :status, type: union(:success, :error)\n  validates_attr :message, type: String, allow_nil: true\nend\n```\n\n### Schema.org Structured Data\n\nThe [Schema.org gem](https://github.com/public-law/schema-dot-org) uses ValidatedObject for type-safe structured data generation.\n\n## Installation\n\nAdd to your Gemfile:\n\n```ruby\ngem 'validated_object'\n```\n\nThen run:\n```bash\nbundle install\n```\n\n## Development\n\nAfter checking out the repo:\n\n```bash\nbin/setup          # Install dependencies\nbundle exec rspec  # Run tests  \nbin/console        # Interactive prompt\n```\n\n## Contributing\n\nBug reports and pull requests welcome on GitHub.\n\n## License\n\nAvailable as open source under the [MIT License](http://opensource.org/licenses/MIT).\n","funding_links":[],"categories":["Ruby"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpublic-law%2Fvalidated_object","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpublic-law%2Fvalidated_object","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpublic-law%2Fvalidated_object/lists"}