Skip to content

Instantly share code, notes, and snippets.

@johnlane
Created October 1, 2015 10:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnlane/603aa9df77834d804e5c to your computer and use it in GitHub Desktop.
Save johnlane/603aa9df77834d804e5c to your computer and use it in GitHub Desktop.
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
Copy link
Author

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