Skip to content

Defining more resources

E. Lynette Rayle edited this page Oct 22, 2020 · 4 revisions

back to Introduction

Goals

  • Define two more custom resources (Page, and CoverArt).

Defining additional resources

The following resources will be used throughout the tutorial.

Edit app/resources/page.rb to contain:

# frozen_string_literal: true
class Page < Valkyrie::Resource
  attribute :alternate_ids, Valkyrie::Types::Array.of(Valkyrie::Types::ID)
  attribute :page_num, Valkyrie::Types::String          
  attribute :structure, Valkyrie::Types::Strict::String
  attribute :image_id, Valkyrie::Types::ID              # ID of stored file for image
end

Edit app/resources/cover_art.rb to contain:

# frozen_string_literal: true
class CoverArt < Valkyrie::Resource
  attribute :alternate_ids, Valkyrie::Types::Array.of(Valkyrie::Types::ID)
  attribute :artists, Valkyrie::Types::Set.of(Valkyrie::Types::Strict::String)
  attribute :image_id, Valkyrie::Types::ID
end

Edit app/resources/book.rb and uncomment attribute :cover_art so that the file contains:

# frozen_string_literal: true
class Book < Valkyrie::Resource
  attribute :alternate_ids, Valkyrie::Types::Array
              .of(Valkyrie::Types::ID)
  attribute :title, Valkyrie::Types::Set
              .of(Valkyrie::Types::String)
              .meta(ordered: true)
  attribute :author, Valkyrie::Types::Set
              .of(Valkyrie::Types::Strict::String)
              .meta(ordered: true)
  attribute :series, Valkyrie::Types::Strict::String  
  attribute :member_ids, Valkyrie::Types::Array
              .of(Valkyrie::Types::ID).optional
  attribute :cover_art, Valkyrie::Types::Array
              .of(CoverArt)                            
end

SPOTCHECK

Run the following in a new rails console (bundle exec rails console) to confirm resources are working as expected.

Create a page resource

> page1 = Page.new
> page1.alternate_ids = 'p1'          
 => "p1"
> page1.page_num = 1                  
 => 1
> page1.structure = "title page"      
 => "title page"

Create a cover art resource

First, try creating with the wrong attribute name, in this case artist instead of artists. Notice that the value of artist is not used in the resource, and the value of artists is an empty array.

> cover_art = CoverArt.new(alternate_ids: 'ca1', artist: 'Mary GrandPré')
 => #<CoverArt id=nil internal_resource="CoverArt" created_at=nil updated_at=nil new_record=true alternate_ids=[#<Valkyrie::ID:... @id="ca1">] artists=[] image_id=nil>

Now, create the cover art resource using the correct attribute name for artists. Notice that a value is not supplied for image_id, so the value is nil.

> cover_art = CoverArt.new(alternate_ids: 'ca1', artists: 'Mary GrandPré')
 => #<CoverArt id=nil internal_resource="CoverArt" created_at=nil updated_at=nil new_record=true alternate_ids=[#<Valkyrie::ID:... @id="ca1">] artists=["Mary GrandPré"] image_id=nil>

Previous | Next