Class: Scrivito::BasicObj

Inherits:
Object
  • Object
show all
Extended by:
ActiveModel::Naming, ActiveSupport::DescendantsTracker, Associations::ClassMethods, AttributeContent::ClassMethods
Includes:
Associations, AttributeContent
Defined in:
app/cms/scrivito/basic_obj.rb

Overview

Note:

Please do not use BasicObj directly as it is intended as an abstract class. Always use Obj or a subclass of Obj.

The abstract base class for CMS objects.

A CMS object is a collection of properties and their values, as defined by its object class. These properties can be accessed in views, either directly as the object itself is rendered, or indirectly when other objects are rendered. The description of an image, for example, can be retrieved from within any view that requires it, e.g. a page on which the image is displayed.

Direct Known Subclasses

Obj

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Associations::ClassMethods

belongs_to, belongs_to_many, has_many

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class Scrivito::AttributeContent

Class Method Details

.allScrivito::ObjSearchEnumerator

Returns an ObjSearchEnumerator of all Objs. If invoked on a subclass of Obj, the result is restricted to instances of this subclass.

Returns:

Raises:

  • (ScrivitoError)

    if called directly on Scrivito::BasicObj. Use Obj.all instead.



285
286
287
288
289
290
291
292
# File 'app/cms/scrivito/basic_obj.rb', line 285

def self.all
  assert_not_basic_obj('.all')
  if type_computer.special_class?(self)
    Workspace.current.objs.all
  else
    find_all_by_obj_class(name)
  end
end

.attribute(name, type, options = {}) ⇒ Object Originally defined in module AttributeContent::ClassMethods

Defines an attribute.

For the purpose of persisting model data in the CMS, the attributes of the model need to be defined. When defining an attribute, you specify the name under which Scrivito should persist its value as well as the type of content it is meant to contain, and, for the enum and multienum types, the selectable values.

Attributes are inherited. If, for example, the Page model defines a title attribute of the string type, the SpecialPage model, which inherits from Page, is also equipped with title. Inherited attributes can be overridden, i.e. you may redefine title in SpecialPage if you want its type to be html, for example.

Examples:

Defining attributes:

class Page < Obj
  attribute :my_string, :string
  attribute 'my_html', 'my_html'
  attribute :my_enum, :enum, values: %w[a b c], default: 'a'
  attribute :my_multienum, :multienum
end

Page.attribute_definitions
#=> #<Scrivito::AttributeDefinitionCollection>

Page.attribute_definitions[:my_string]
#=> #<Scrivito::AttributeDefinition>

Page.attribute_definitions[:my_string].type
#=> "string"

Page.attribute_definitions[:my_html].type
#=> "html"

Page.attribute_definitions[:my_enum].type
#=> "enum"
Page.attribute_definitions[:my_enum].values
#=> ["a", "b", "c"]

Page.attribute_definitions[:my_multienum].type
#=> "multienum"
Page.attribute_definitions[:my_multienum].values
#=> []

Inheriting attributes:

class Page < Obj
  attribute :title, :string
end

class SpecialPage < Page
end

SpecialPage.attribute_definitions[:title].type
#=> "string"

Overriding inherited attributes:

class Page < Obj
  attribute :title, :string
end

class SpecialPage < Page
  attribute :title, :html
end

Page.attribute_definitions[:title].type
#=> "string"

SpecialPage.attribute_definitions[:title].type
#=> "html"

Specifying valid classes for reference attributes:

class Page < Obj
  attribute :my_reference1, :reference, only: Image
  attribute :my_reference2, :reference, only: [Image, Video]
end

ImageWidget.attribute_definitions[:my_reference1].valid_classes
#=> [Image]

ImageWidget.attribute_definitions[:my_reference2].valid_classes
#=> [Image, Video]

Parameters:

  • name (Symbol, String)

    name of the attribute. The first character must be an ASCII lowercase letter, subsequent characters may also be digits or underscores. Also, the name must not be longer than 50 characters and must not be “id”.

  • type (Symbol, String)

    type of the attribute. Scrivito supports the following types: string, stringlist, html, enum, multienum, widgetlist, reference, referencelist, link, linklist, integer, float and binary.

  • options (Hash) (defaults to: {})

    definition options.

Options Hash (options):

  • :values (Array<Symbol>, Array<String>)

    selectable values for enum and multienum attributes. If no values are provided for attributes of these types, the resulting array of selectable values is empty. Empty string is not allowed as value.

  • :default (Symbol, String)

    custom default value. See DEFAULT_ATTRIBUTE_VALUES for factory defaults. See #default_for for more advanced defaults.

  • :only (Class, Array<Class>)

    specifies (for use in the UI) the valid classes of the values in a reference or a referencelist attribute, e.g. Image or Video. Raises an error if the attribute type is neither reference nor referencelist. If not specified, the UI assumes that any class is valid.

Returns:

  • nil

Raises:

See Also:

.attribute_definitionsScrivito::AttributeDefinitionCollection Originally defined in module AttributeContent::ClassMethods

Returns the attribute definitions.

.create(attributes = {}, context = {}) ⇒ Obj

Create a new Obj in the CMS.

This allows you to set the different attributes of an Obj by providing a hash containing the attribute names as keys and the corresponding values you want to set. The defaults set via Obj.default_for are taken into account.

Examples:

Provide reference lists as an Array of Obj.

Obj.create(:reference_list => [other_obj])

Passing an Obj allows you to set a reference.

Obj.create(:reference => other_obj)

You can upload files by passing a Ruby File object.

Obj.create(:blob => File.new("image.png"))

A link list can be set as an Array of Links.

Obj.create(:link_list => [
  # external link
  Link.new(:url => "http://www.example.com", :title => "Example"),
  # internal link
  Link.new(:obj => other_obj, :title => "Other Obj")
])

Passing a Link allows you to set a link.

Obj.create(
  external_link: Link.new(url: 'http://www.example.com', title: 'Example'),
  internal_link: Link.new(obj: other_obj, title: 'Other Obj')
)

Date attributes accept Time, Date and their subclasses (DateTime, for example).

Obj.create(:date => Time.new)
Obj.create(:date => Date.now)

String, html and enum attributes can be set by passing a String value.

Obj.create(:title => "My Title")

Multienum attributes can be set using an Array of Strings.

Obj.create(:tags => ["ruby", "rails"])

Simply pass an Array of Widgets to populate a widget field. See Widget#copy on how to copy a widget.

# Add new widgets
Obj.create(:widgets => [Widget.new(_obj_class: 'TitleWidget', title: 'My Title')])

# Add a copy of a widget
Obj.create(:widgets => [another_obj.widgets.first.copy])

# Change a widget field
obj.update(:widgets => [obj.widgets.first])

# Clear a widget field
obj.update(:widgets => [])

Parameters:

  • attributes (Hash) (defaults to: {})

    of the new obj

  • context (Hash) (defaults to: {})

    in which the object is created

Options Hash (context):

Returns:

  • (Obj)

    the newly created Obj

Raises:

  • (ArgumentError)

    if called on Obj without _obj_class attribute.

See Also:



139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
# File 'app/cms/scrivito/basic_obj.rb', line 139

def self.create(attributes = {}, context = {})
  attributes = with_default_id_attribute(attributes)
  if obj_class = extract_obj_class_from_attributes(attributes)
    obj_class.create(attributes, context)
  else
    attributes = build_attributes_with_defaults(attributes, context)
    attributes = prepare_attributes_for_instantiation(attributes)
    extraction, api_attributes = prepare_attributes_for_rest_api(attributes)

    workspace = Workspace.current
    obj_data = workspace.create_obj(obj: api_attributes)
    obj = BasicObj.instantiate(obj_data)
    obj.revision = workspace.revision

    extraction.notify_persisted(obj)
    obj
  end
end

.default_for(attribute_name, &block) ⇒ Object Originally defined in module AttributeContent::ClassMethods

Sets the default value of an attribute defined by #attribute or for the built-in attributes _path and _permalink.

If Obj.create or Widget.new are called without providing a value for a specific custom attribute, the block is called, and its return value is used as the initial value of this attribute.

The block is called with two parameters.

The first parameter is an ActiveSupport::HashWithIndifferentAccess containing the attributes that were passed to Obj.create or Widget.new.

The second parameter, context, is a hash. If the default_for callback is triggered by a UI user creating a CMS object or a Widget, Scrivito places the :scrivito_user and the :current_page (originating from the UI calling the creation method) into this hash. :current_page won’t be present in the context if the user creates the object or widget while viewing a page which isn’t a CMS object. The context hash is empty if the object or widget is not created using the UI but, for example, via the console.

Examples:

Setting a simple default:

class MyPage < Obj
  attribute :title, :string
  default_for(:title) { 'Spam' }
end

my_page = MyPage.create
my_page.title # => 'Spam'

A default depending on the given attributes:

class MyPage < Obj
  attribute :title, :string

  default_for :title do |attributes|
    if (path = attributes[:_path]) && path.starts_with('/de')
      'Hier den Titel eingeben'
    else
      'Your title here'
    end
  end
end

my_page = MyPage.create(_path: '/en/test')
my_page.title # => 'Your title here'

my_page = MyPage.create(_path: '/de/test')
my_page.title # => 'Hier den Titel eingeben'

A more complex default, depending on the given attributes and the current user:

class MyPage < Obj
  attribute :title, :string

  default_for :title do |attributes, context|
    if use_german_title?(context[:scrivito_user], attributes[:_path])
      'Hier den Titel eingeben'
    else
      'Your title here'
    end
  end

  private

  #
  # Assuming there is a +MyUser+ model equipped with a +preferences+ method which
  # returns the preferences of the current user.
  # The +email+ of a +MyUser+ is the +id+ of the corresponding +Scrivito::User+ as set in
  # +Scrivito::Configuration.editing_auth+.
  #
  def use_german_title?(scrivito_user, path)
    scrivito_user && MyUser.find_by(email: scrivito_user.id).preferences[:locale] == 'de' ||
      path && path.starts_with?('/de')
  end
end

MyUser.find_by(email: '[email protected]').preferences[:locale] # => 'en'
alice = Scrivito::User.define('[email protected]')

my_page = MyPage.create({_path: '/de/test'}, alice)
my_page.title # => 'Your title here'

MyUser.find_by(email: '[email protected]').preferences[:locale] # => 'de'
bob = Scrivito::User.define('[email protected]')

my_page = MyPage.create({_path: '/en/test'}, bob)
my_page.title # => 'Hier den Titel eingeben'

Parameters:

  • attribute_name (Symbol, String)

    the name of the attribute.

  • block (Proc)

    that returns the default value.

Returns:

  • nil

Raises:

See Also:

.description_for_editorString Originally defined in module AttributeContent::ClassMethods

Short description of a CMS object or widget type for the UI.

The description is displayed when adding new pages or widgets, for example. As a general rule, it is used whenever no widget or object instance is available. If there is, the BasicObj#description_for_editor and, respectively, BasicWidget#description_for_editor instance methods are used instead.

This method can be overridden to customize the description displayed to editors.

Returns:

  • (String)

    short description of a CMS object or widget type for the UI

.find(id_or_list) ⇒ Obj+

Find an Obj by its id. If the parameter is an Array of ids, the list of corresponding objects is returned.

Examples:

Find several CMS objects at once:

Obj.find(['id1', 'id2'])

Parameters:

  • id_or_list (String, Integer, Array<String, Integer>)

Returns:



212
213
214
# File 'app/cms/scrivito/basic_obj.rb', line 212

def self.find(id_or_list)
  Workspace.current.objs.find(id_or_list)
end

.find_all_by_name(name) ⇒ Scrivito::ObjSearchEnumerator

Returns an ObjSearchEnumerator of all CMS objects with the given name.

Parameters:

  • name (String)

    Name of the Obj.

Returns:



326
327
328
# File 'app/cms/scrivito/basic_obj.rb', line 326

def self.find_all_by_name(name)
  where(:_name, :equals, name)
end

.find_all_by_obj_class(obj_class) ⇒ Scrivito::ObjSearchEnumerator

Returns an ObjSearchEnumerator of all CMS objects with the given obj_class.

Parameters:

  • obj_class (String)

    name of the object class.

Returns:



298
299
300
# File 'app/cms/scrivito/basic_obj.rb', line 298

def self.find_all_by_obj_class(obj_class)
  Workspace.current.objs.find_all_by_obj_class(obj_class)
end

.find_by_name(name) ⇒ Obj

Find an Obj with the given name. If several objects with the given name exist, an arbitrary one is chosen and returned. If no Obj with this name exists, nil is returned.

Parameters:

  • name (String)

    Name of the Obj.

Returns:



318
319
320
# File 'app/cms/scrivito/basic_obj.rb', line 318

def self.find_by_name(name)
  where(:_name, :equals, name).batch_size(1).first
end

.find_by_path(path) ⇒ Obj

Find the Obj with the given path. Returns nil if no matching Obj exists.

Parameters:

  • path (String)

    Path of the Obj.

Returns:



307
308
309
310
# File 'app/cms/scrivito/basic_obj.rb', line 307

def self.find_by_path(path)
  Workspace.current.objs.find_one_by(:path, path,
      type_computer.obj_class_name_for_type(self))
end

Returns the Obj with the given permalink, or nil if no matching Obj exists.

Parameters:

  • permalink (String)

    The permalink of the Obj.

Returns:



335
336
337
338
# File 'app/cms/scrivito/basic_obj.rb', line 335

def self.find_by_permalink(permalink)
  Workspace.current.objs.find_one_by(:permalink, permalink,
      type_computer.obj_class_name_for_type(self))
end

.find_by_permalink!(permalink) ⇒ Obj

Returns the Obj with the given permalink, or raises ResourceNotFound if no matching Obj exists.

Parameters:

  • permalink (String)

    The permalink of the Obj.

Returns:



346
347
348
349
350
351
# File 'app/cms/scrivito/basic_obj.rb', line 346

def self.find_by_permalink!(permalink)
  find_by_permalink(permalink) or begin
    model_name = type_computer.obj_class_name_for_type(self) || 'Obj'
    raise ResourceNotFound, "Could not find #{model_name} with permalink '#{permalink}'"
  end
end

.find_including_deleted(id_or_list) ⇒ Obj+

Find an Obj by its id. If the parameter is an Array containing ids, return a list of corresponding objects. The results include deleted objects as well.

Parameters:

  • id_or_list (String, Integer, Array<String, Integer>)

Returns:



226
227
228
# File 'app/cms/scrivito/basic_obj.rb', line 226

def self.find_including_deleted(id_or_list)
  Workspace.current.objs.find_including_deleted(id_or_list)
end

.hide_from_editorObject Originally defined in module AttributeContent::ClassMethods

This method prevents UI users from creating Objs or Widgets of the given type. It does not prevent adding such objects programatically.

By default, hide_from_editor is false.

Examples:

Hiding error pages:

class ErrorPage < Obj
  hide_from_editor
end

Hiding admin widgets:

class AdminWidget < Widget
  hide_from_editor
end

.restore(obj_id) ⇒ Object

Restores a previously deleted Obj.

Raises:



164
165
166
167
168
169
# File 'app/cms/scrivito/basic_obj.rb', line 164

def self.restore(obj_id)
  Workspace.current.assert_revertable
  base_revision_path = "revisions/#{Workspace.current.base_revision_id}/objs/#{obj_id}"
  obj_attributes = CmsRestApi.get(base_revision_path).merge('_id' => obj_id)
  Workspace.current.api_request(:post, '/objs', obj: obj_attributes)
end

.rootObj

Returns the root Obj, the object whose path is “/”.

Returns:



514
515
516
517
518
519
# File 'app/cms/scrivito/basic_obj.rb', line 514

def self.root
  BasicObj.find_by_path('/') or raise ResourceNotFound,
      '"Obj.root" not found: There is no "Obj" with path "/". '\
      'Maybe you forgot the migration when setting up your Scrivito application? '\
      'Try "bundle exec rake scrivito:migrate scrivito:migrate:publish".'
end

.valid_page_classes_beneath(parent_path) ⇒ NilClass, Array<Class>

Hook method that lets you control which page classes are made available for pages with the given path. Override it to allow only specific classes or none at all. Must return either NilClass, or Array.

Be aware that the given argument is a parent path. E.g., when creating a page whose path is /products/shoes, the argument must be /products. The given parent path can also be NilClass.

If NilClass is returned, all page classes are made available. By default, NilClass is returned.

If an Array is returned, it is expected to contain the available classes. The order of the classes is preserved.

Parameters:

  • parent_path (String, NilClass)

    Path of the parent obj

Returns:

  • (NilClass, Array<Class>)


370
371
# File 'app/cms/scrivito/basic_obj.rb', line 370

def self.valid_page_classes_beneath(parent_path)
end

.where(field, operator, value, boost = nil) ⇒ Scrivito::ObjSearchEnumerator

Note:

If invoked on a subclass of Obj, the result will be restricted to instances of this

Returns an ObjSearchEnumerator with the given initial subquery consisting of the four arguments.

Note that field and value can also be arrays for searching several fields or searching for several values.

subclass.

ObjSearchEnumerators can be chained using one of the chainable methods (e.g. ObjSearchEnumerator#and and ObjSearchEnumerator#and_not).

Examples:

Look for objects containing “Lorem”, boosting headline matches:

Obj.where(:*, :contains, 'Lorem', headline: 2).to_a

Look for the first 10 objects whose object class is “Pressrelease” and whose title contains “quarterly”:

Obj.where(:_obj_class, :equals, 'Pressrelease').and(:title, :contains, 'quarterly').take(10)

Look for all objects whose class is “Item”. The path should start with a defined location. Furthermore, select only items of a particular category:

Obj.where(:_obj_class, :equals, 'Item').and(:_path, :starts_with, '/en/items/').select do |item|
  item.categories.include?(category)
end

Find CMS objects linking to my_image through any link or reference:

Obj.where(:*, :links_to, my_image)

Find BlogPostPage objects linking to my_image1 or my_image2 through any link or reference:

BlogPostPage.where(:*, :links_to, [my_img1, my_img2])

Find all objects of the BlogPost class that reference author_obj via the authors referencelist attribute.

BlogPost.where(:authors, :refers_to, author_obj)

Parameters:

Returns:

Raises:



270
271
272
273
274
275
276
277
278
# File 'app/cms/scrivito/basic_obj.rb', line 270

def self.where(field, operator, value, boost = nil)
  assert_not_basic_obj('.where')
  if type_computer.special_class?(self)
    Workspace.current.objs.where(field, operator, value, boost)
  else
    Workspace.current.objs.where(:_obj_class, :equals, name)
        .and(field, operator, value, boost)
  end
end

Instance Method Details

#[](key) ⇒ Object

Returns the value of a system or custom attribute specified by its name. Passing an invalid key will not raise an error but return nil.



687
688
689
690
691
692
693
694
# File 'app/cms/scrivito/basic_obj.rb', line 687

def [](key)
  key = key.to_s
  if SYSTEM_KEYS.include?(key)
    read_attribute(key)
  else
    super
  end
end

#alt_descriptionString

The alt description of an Obj used for ScrivitoHelper#scrivito_image_tag.

By default, this method returns the title of the Obj.

You can customize this part by overriding #alt_description.

Returns:

  • (String)


595
596
597
# File 'app/cms/scrivito/basic_obj.rb', line 595

def alt_description
  title
end

#ancestorsArray<Obj>

Returns an Array of all the ancestor objects, starting at the root and ending at the parent of this object.

Returns:



474
475
476
477
478
479
480
481
482
# File 'app/cms/scrivito/basic_obj.rb', line 474

def ancestors
  return [] unless child_path?

  ancestor_paths = parent_path.scan(/\/[^\/]+/).inject([""]) do |list, component|
    list << list.last + component
  end
  ancestor_paths[0] = "/"
  Workspace.current.objs.find_by_paths(ancestor_paths)
end

#apply_image_transformation?Boolean

Deprecated.

Has no effect anymore: Image transformation will be applied if possible.

Returns:

  • (Boolean)


622
623
624
625
# File 'app/cms/scrivito/basic_obj.rb', line 622

def apply_image_transformation?
  Scrivito::Deprecation.warn(
    'Scrivito::BasicObj#apply_image_transformation? is deprecated and has no effect anymore.')
end

#as_json(options = nil) ⇒ Hash Originally defined in module AttributeContent

Note:

Override it in subclasses to fit your needs.

Returns a hash to be used for the JSON serialization.

Parameters:

  • options (Hash) (defaults to: nil)

Returns:

  • (Hash)

See Also:

Searches for CMS objects containing one or more attributes linking to this CMS object.

So the search returns the CMS objects in which at least one html, link, linklist, reference or referencelist attribute links to this CMS object.

Attributes inside Widgets are considered, too.

#binaryBinary?

This method is intended for CMS objects that represent binary resources like images or PDF documents. If the Obj represents a binary file, an instance of Scrivito::Binary is returned.

This method returns the blob attribute if its type is binary.

Returns:



860
861
862
# File 'app/cms/scrivito/basic_obj.rb', line 860

def binary
  self[:blob] if self[:blob].is_a?(Binary)
end

#binary?Boolean

This method indicates whether the Obj represents binary data. Binaries are handled differently in that they are not rendered using the normal layout but sent as a file. Examples of binary resources are Images or PDFs.

Every Obj that has a blob attribute of the binary type is considered a binary

Returns:

  • (Boolean)

    true if this Obj represents a binary resource.



613
614
615
616
# File 'app/cms/scrivito/basic_obj.rb', line 613

def binary?
  blob_attribute_definition = attribute_definitions['blob']
  blob_attribute_definition.present? && blob_attribute_definition.type == 'binary'
end

#binary_content_typeString?

This method returns the content type of the binary of this Obj if the binary is set.

Returns:

  • (String, nil)


874
875
876
# File 'app/cms/scrivito/basic_obj.rb', line 874

def binary_content_type
  binary.try(:content_type)
end

#binary_lengthInteger

This method returns the byte length of the binary of the Obj.

Returns:

  • (Integer)

    If no binary is set, 0 is returned.



867
868
869
# File 'app/cms/scrivito/basic_obj.rb', line 867

def binary_length
  binary.try(:content_length) || 0
end

#binary_urlString?

This method returns the URL under which the content of this binary is available to the public if the binary is set.

See Scrivito::Binary#url for details

Returns:

  • (String, nil)


884
885
886
# File 'app/cms/scrivito/basic_obj.rb', line 884

def binary_url
  binary.try(:url)
end

#bodyString

Returns the body (main content) of the Obj for non-binary objects. Returns nil for binary objects.

Returns:

  • (String)


844
845
846
847
848
849
850
# File 'app/cms/scrivito/basic_obj.rb', line 844

def body
  if binary?
    nil
  else
    read_attribute('body')
  end
end

#childrenArray<Obj>

Returns a list of all child Objs.

Returns:



487
488
489
490
491
# File 'app/cms/scrivito/basic_obj.rb', line 487

def children
  return [] unless path

  workspace.objs.find_by_parent_path(path)
end

#controller_action_nameString

This method determines the action to be invoked when the Obj is requested. The default action is ‘index’. Override this method to force a different action to be used.

Returns:

  • (String)


546
547
548
# File 'app/cms/scrivito/basic_obj.rb', line 546

def controller_action_name
  "index"
end

#controller_nameString

This method determines the controller to be invoked when the Obj is requested. By default, a controller matching the obj_class of the Obj is used. If the controller does not exist, the CmsController is used as a fallback. Override this method to force a different controller to be used.

Returns:

  • (String)


537
538
539
# File 'app/cms/scrivito/basic_obj.rb', line 537

def controller_name
  obj_class
end

#copy(options = {}) ⇒ Obj

Creates a copy of the Obj.

Examples:

Copy a blog post:

blog_post = Obj.find_by_path('/blog/first_post')
blog_post.copy(_path: '/blog/second_post')

Parameters:

  • options (Hash) (defaults to: {})

Options Hash (options):

  • :_path (String, Symbol) — default: nil

    the path of the copy.

  • :_id (String, Symbol) — default: nil

    the id of the copy.

  • :_permalink (String, Symbol) — default: nil

    the permalink of the copy.

Returns:

  • (Obj)

    the created copy

Raises:

  • (ArgumentError)

    if options includes invalid keys.



439
440
441
442
443
444
445
446
447
# File 'app/cms/scrivito/basic_obj.rb', line 439

def copy(options={})
  options = options.stringify_keys.assert_valid_keys('_path', '_id', '_permalink')
  attributes_for_copy = self.class.with_default_id_attribute(copyable_attributes)
  attributes_for_copy = attributes_for_copy.with_indifferent_access.merge(options)
  attributes_for_copy = copy_binaries(attributes_for_copy)

  json = workspace.api_request(:post, '/objs', obj: attributes_for_copy)
  self.class.find(json['_id'])
end

#created_atnil, ActiveSupport::TimeWithZone

Note:

If the custom attribute created_at is defined, this value will be returned instead of the system attribute _created_at. To access the system attribute regardless of a custom attribute, call obj[:_created_at].

Returns:

  • (nil, ActiveSupport::TimeWithZone)


727
728
729
# File 'app/cms/scrivito/basic_obj.rb', line 727

def created_at
  read_custom_or_system_attribute('created_at')
end

#description_for_editorObject

This method determines the description shown in the UI. It defaults to #display_title. It can be overridden by a custom value.



570
571
572
# File 'app/cms/scrivito/basic_obj.rb', line 570

def description_for_editor
  display_title
end

#destroyObject

Destroys the Obj in the current Workspace.



451
452
453
454
455
456
# File 'app/cms/scrivito/basic_obj.rb', line 451

def destroy
  if children.any?
    raise ClientError.new(I18n.t('scrivito.errors.models.basic_obj.has_children'))
  end
  workspace.api_request(:delete, "/objs/#{id}")
end

#display_titleString

Calculates an appropriate title for an Obj.

Returns:

  • (String)

    Scrivito::Binary#filename if Obj is binary and has a filename.

  • (String)

    #title if Obj has a non-empty title.

  • (String)

    falls back to Obj.description_for_editor.



583
584
585
# File 'app/cms/scrivito/basic_obj.rb', line 583

def display_title
  (binary_title || title).presence || self.class.description_for_editor
end

#file_extensionString

Returns the name extension of the Obj (the part after the last dot). Returns an empty string if the name of the Obj doesn’t have an extension.

Returns:

  • (String)


836
837
838
# File 'app/cms/scrivito/basic_obj.rb', line 836

def file_extension
  File.extname(name)[1..-1] || ""
end

#first_published_atnil, ActiveSupport::TimeWithZone

Note:

If the custom attribute first_published_at is defined, this value will be returned instead of the system attribute _first_published_at. To access the system attribute regardless of a custom attribute, call obj[:_first_published_at].

Returns:

  • (nil, ActiveSupport::TimeWithZone)


742
743
744
# File 'app/cms/scrivito/basic_obj.rb', line 742

def first_published_at
  read_custom_or_system_attribute('first_published_at')
end

#idObject



190
191
192
# File 'app/cms/scrivito/basic_obj.rb', line 190

def id
  read_attribute('_id')
end

#last_changedActiveSupport::TimeWithZone

Returns:

  • (ActiveSupport::TimeWithZone)


733
734
735
# File 'app/cms/scrivito/basic_obj.rb', line 733

def last_changed
  read_attribute('_last_changed')
end

#meta_dataScrivito::MetaDataCollection

Allows accessing the meta data for binary Objs.

Examples:

Accessing meta data

obj.['width'] # => 150
obj.['content_type'] # => 'image/jpeg'

Returns:

  • (Scrivito::MetaDataCollection)

    The collection of available meta data

See Also:

  • List of available meta data attributes.


899
900
901
# File 'app/cms/scrivito/basic_obj.rb', line 899

def 
  binary.try(:meta_data) || MetaDataCollection.new({})
end

#nameObject

Returns the name of the Obj. The name is the last component of a path.



503
504
505
506
507
508
509
# File 'app/cms/scrivito/basic_obj.rb', line 503

def name
  if child_path?
    path.match(/[^\/]+$/)[0]
  else
    ""
  end
end

#obj_classString Originally defined in module AttributeContent

Returns the object class name of this CMS object.

Examples:

BlogPost.all.first.obj_class
#=> "BlogPost"
FrenchBlog::BlogPost.all.first.obj_class
#=> "FrenchBlog::BlogPost"

GermanBlog::BlogPost.all.first.obj_class
#=> "GermanBlog::BlogPost"

Returns:

  • (String)

#obj_class_nameString Originally defined in module AttributeContent

Deprecated.

Use #obj_class instead.

Returns the object class name of this CMS object.

Returns:

  • (String)

#parentObject

Returns the Obj that is the parent of this Obj. Returns nil for the root Obj.



465
466
467
468
469
# File 'app/cms/scrivito/basic_obj.rb', line 465

def parent
  if child_path?
    workspace.objs.find_by_path(parent_path)
  end
end

#pathObject

Returns the path of the Obj as a String.



497
498
499
# File 'app/cms/scrivito/basic_obj.rb', line 497

def path
  read_attribute('_path')
end

Returns the permalink of the Obj.



527
528
529
# File 'app/cms/scrivito/basic_obj.rb', line 527

def permalink
  read_attribute('_permalink')
end

#published_atnil, ActiveSupport::TimeWithZone

Note:

If the custom attribute published_at is defined, this value will be returned instead of the system attribute _published_at. To access the system attribute regardless of a custom attribute, call obj[:_published_at].

Returns:

  • (nil, ActiveSupport::TimeWithZone)


751
752
753
# File 'app/cms/scrivito/basic_obj.rb', line 751

def published_at
  read_custom_or_system_attribute('published_at')
end

#reloadObject

Reloads the attributes of this Obj from the database. Note that the Ruby class of this Obj instance will NOT change, even if the obj_class in the database has changed.



710
711
712
713
# File 'app/cms/scrivito/basic_obj.rb', line 710

def reload
  workspace.reload
  reload_data
end

#revertObject

Note:

This method does not support Objs that are new. Please use Obj#destroy to destroy them.

Note:

This method does not support Objs that are deleted. Please use Obj.restore to restore them.

Reverts all changes made to the Obj in the current workspace.

Raises:



957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
# File 'app/cms/scrivito/basic_obj.rb', line 957

def revert
  assert_revertable

  if modification == Modification::EDITED
    base_revision_path = "revisions/#{workspace.base_revision_id}/objs/#{id}"
    previous_attributes = CmsRestApi.get(base_revision_path).except('_id')
    previous_widget_pool = previous_attributes['_widget_pool']

    ids_of_new_widgets = read_widget_pool.keys - previous_widget_pool.keys
    ids_of_new_widgets.each { |widget_id| previous_widget_pool[widget_id] = nil }

    previous_attributes = reset_blank_attributes(previous_attributes)

    workspace.api_request(:put, "/objs/#{id}", obj: previous_attributes)
    reload
  end
end

#root?Boolean

Returns true if this Obj is the root Obj.

Returns:

  • (Boolean)


629
630
631
# File 'app/cms/scrivito/basic_obj.rb', line 629

def root?
  path == "/"
end

#slugString

This method is used to calculate a part of a URL of this Obj.

The routing schema: <obj.slug>-<obj.id>

The default is parameterize on obj.title.

You can customize this part by overriding #slug.

Returns:

  • (String)


560
561
562
# File 'app/cms/scrivito/basic_obj.rb', line 560

def slug
  (title || '').parameterize
end

#sorted_toclistArray<Obj>

Returns a list of children that are sorted according to the order specifed in the child_order attribute. The same sort order is used when rendering navigations using the scrivito_tag_list helper.

Returns:



651
652
653
# File 'app/cms/scrivito/basic_obj.rb', line 651

def sorted_toclist
  sort_toclist(toclist)
end

#titleObject



600
601
602
# File 'app/cms/scrivito/basic_obj.rb', line 600

def title
  read_attribute('title')
end

#toclist(*args) ⇒ Array<Obj>

Returns a list of children excluding the binary? ones unless :all is specfied. This is useful for creating navigations.

Returns:



637
638
639
640
641
642
# File 'app/cms/scrivito/basic_obj.rb', line 637

def toclist(*args)
  return [] if binary?
  toclist = children
  toclist = toclist.reject { |toc| toc.binary? } unless args.include?(:all)
  toclist.sort_by(&:id)
end

#update(attributes) ⇒ Object

Update the Obj using the attributes provided.

For an overview of the values you can set via this method, see the documentation of Obj.create.

Additionally, update accepts a _widget_pool hash in attributes to modify widgets. The keys of _widget_pool are widget instances, the values are the modified attributes of these particular widgets.

Examples:

Update the URL of a link:

link = obj.my_link
link.url = "http://www.example.com"
obj.update(my_link: link)

Update binary attributes:

obj.update(blob: img_obj.binary)
obj.update(thumbnail: File.new("/path/to/small.jpg"))

Remove the first and the last widget from a widget field:

obj.update(
  my_widget_field: obj[:my_widget_field][1..-2]
)

Move the widget_to_move widget from the left widget field of the two_column_widget1 widget to left of two_column_widget2:

obj.update(
  _widget_pool: {
    two_column_widget1 => {left: two_column_widget1.left - [widget_to_move]},
    two_column_widget2 => {left: two_column_widget2.left + [widget_to_move]}
  },
  headline: "Some widgets were moved!"
)

Move the widget_to_move widget from the right widget field of the two_column_widget1 widget to the top-level main_content widget field:

obj.update(
  main_content: @obj.main_content + [widget_to_move],
  _widget_pool: {
    two_column_widget1 => {
      right: two_column_widget1.right - [widget_to_move]
    }
  }
)

Parameters:

  • attributes (Hash)


421
422
423
424
425
426
# File 'app/cms/scrivito/basic_obj.rb', line 421

def update(attributes)
  extraction, api_attributes = prepare_attributes_for_rest_api(attributes)
  update_data(workspace.update_obj(id, obj: api_attributes))
  extraction.notify_persisted(self)
  self
end

#valid_widget_classes_for(field_name) ⇒ nil, Array<Class> Originally defined in module AttributeContent

Hook method that lets you control the widget classes that are made available for adding instances of them to this page or widget. Override it to allow only specific classes or none at all. Must return either NilClass, or Array.

If nil is returned (default), all widget classes will be available for this page or widget.

If an Array is returned, it is expected to include the permitted classes. Their order is preserved as they are offered to the user via the widget browser.

Parameters:

  • field_name (String)

    Name of the widget attribute.

Returns:

  • (nil, Array<Class>)

See Also:

#widgetsScrivito::WidgetCollection

Allows accessing the Widgets of this Obj.

Examples:

Access a widget by its id

obj.widgets['widget_id']

Returns:



934
935
936
# File 'app/cms/scrivito/basic_obj.rb', line 934

def widgets
  @widgets ||= WidgetCollection.new(self)
end