Skip to content

Instantly share code, notes, and snippets.

@johnlane

johnlane/cell.rb

Created Oct 1, 2015
Embed
What would you like to do?
Widget wrapper around cell
# app/concepts/widget/cell.rb
# A very basic "Widget" that is a container of Cell objects
# When rendered, it recursively renders all cells that it
# contains.
class Widget < Cell::Concept
attr_reader :parent
attr_reader :children
# Create a new widget
# All widgets are created as orphans
def initialize(*args)
super
@parent = nil
@children = []
end
# Accept an orphan widget as a child
def <<(w)
if w.parent.nil?
@children << w
w.parent = self
else
raise Widget::HasParent
end
end
def show(options={})
out = ''
@children.each { |c| out << c.show(options) }
out.html_safe
end
protected
attr_writer :parent
end
@johnlane

This comment has been minimized.

Copy link
Owner Author

@johnlane johnlane commented Oct 1, 2015

I use this to build dynamic messaging object (flash on steroids) that is accessible from anywhere. Any method can write a message and it will be rendered in the layout.

They can do this:

    Message.now( {error: t('.failure')}, scope: 'sign_in')

which makes use of the below, where @messages is a widget cell.

    # send messages into the current action
    def now(messages, options={})
      send :now, messages, options
    end 

    def send(mode, messages, options={})
      @messages ||= Widget.new

      if messages.respond_to? :each
        messages.each do |type,text|
          case mode
          when :now
            @messages << Message::Cell.new({type => text}, options)
          when :next
            @flash[type] = text
          end 
        end 
      else
        raise InvalidMessage
      end 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.