Coder Social home page Coder Social logo

cells's Introduction

Cells

View Components for Ruby and Rails.

Zulip Chat TRB Newsletter Build Status Gem Version

Overview

Cells allow you to encapsulate parts of your UI into components into view models. View models, or cells, are simple ruby classes that can render templates.

Nevertheless, a cell gives you more than just a template renderer. They allow proper OOP, polymorphic builders, nesting, view inheritance, using Rails helpers, asset packaging to bundle JS, CSS or images, simple distribution via gems or Rails engines, encapsulated testing, caching, and integrate with Trailblazer.

Full Documentation

Cells is part of the Trailblazer framework. Full documentation is available on the project site.

Cells is completely decoupled from Rails. However, Rails-specific functionality is to be found here.

Rendering Cells

You can render cells anywhere and as many as you want, in views, controllers, composites, mailers, etc.

Rendering a cell in Rails ironically happens via a helper.

<%= cell(:comment, @comment) %>

This boils down to the following invocation, that can be used to render cells in any other Ruby environment.

CommentCell.(@comment).()

You can also pass the cell class in explicitly:

<%= cell(CommentCell, @comment) %>

In Rails you have the same helper API for views and controllers.

class DashboardController < ApplicationController
  def dashboard
    @comments = cell(:comment, collection: Comment.recent)
    @traffic  = cell(:report, TrafficReport.find(1)).()
  end

Usually, you'd pass in one or more objects you want the cell to present. That can be an ActiveRecord model, a ROM instance or any kind of PORO you fancy.

Cell Class

A cell is a light-weight class with one or multiple methods that render views.

class CommentCell < Cell::ViewModel
  property :body
  property :author

  def show
    render
  end

private
  def author_link
    link_to "#{author.email}", author
  end
end

Here, show is the only public method. By calling render it will invoke rendering for the show view.

Logicless Views

Views come packaged with the cell and can be ERB, Haml, or Slim.

<h3>New Comment</h3>
  <%= body %>

By <%= author_link %>

The concept of "helpers" that get strangely copied from modules to the view does not exist in Cells anymore.

Methods called in the view are directly called on the cell instance. You're free to use loops and deciders in views, even instance variables are allowed, but Cells tries to push you gently towards method invocations to access data in the view.

File Structure

In Rails, cells are placed in app/cells or app/concepts/. Every cell has their own directory where it keeps views, assets and code.

app
├── cells
│   ├── comment_cell.rb
│   ├── comment
│   │   ├── show.haml
│   │   ├── list.haml

The discussed show view would reside in app/cells/comment/show.haml. However, you can set any set of view paths you want.

Invocation Styles

In order to make a cell render, you have to call the rendering methods. While you could call the method directly, the preferred way is the call style.

cell(:comment, @song).()       # calls CommentCell#show.
cell(:comment, @song).(:index) # calls CommentCell#index.

The call style respects caching.

Keep in mind that cell(..) really gives you the cell object. In case you want to reuse the cell, need setup logic, etc. that's completely up to you.

Parameters

You can pass in as many parameters as you need. Per convention, this is a hash.

cell(:comment, @song, volume: 99, genre: "Jazz Fusion")

Options can be accessed via the @options instance variable.

Naturally, you may also pass arbitrary options into the call itself. Those will be simple method arguments.

cell(:comment, @song).(:show, volume: 99)

Then, the show method signature changes to def show(options).

Testing

A huge benefit from "all this encapsulation" is that you can easily write tests for your components. The API does not change and everything is exactly as it would be in production.

html = CommentCell.(@comment).()
Capybara.string(html).must_have_css "h3"

It is completely up to you how you test, whether it's RSpec, MiniTest or whatever. All the cell does is return HTML.

In Rails, there's support for TestUnit, MiniTest and RSpec available, along with Capybara integration.

Properties

The cell's model is available via the model reader. You can have automatic readers to the model's fields by using ::property.

class CommentCell < Cell::ViewModel
  property :author # delegates to model.author

  def author_link
    link_to author.name, author
  end
end

HTML Escaping

Cells per default does no HTML escaping, anywhere. Include Escaped to make property readers return escaped strings.

class CommentCell < Cell::ViewModel
  include Escaped

  property :title
end

song.title                 #=> "<script>Dangerous</script>"
Comment::Cell.(song).title #=> &lt;script&gt;Dangerous&lt;/script&gt;

Properties and escaping are documented here.

Installation

Cells runs with any framework.

gem "cells"

For Rails, please use the cells-rails gem. It supports Rails >= 4.0.

gem "cells-rails"

Lower versions of Rails will still run with Cells, but you will get in trouble with the helpers. (Note: we use Cells in production with Rails 3.2 and Haml and it works great.)

Various template engines are supported but need to be added to your Gemfile.

gem "cells-erb"

In Rails, this is all you need to do. In other environments, you need to include the respective module into your cells.

class CommentCell < Cell::ViewModel
  include ::Cell::Erb # or Cell::Hamlit, or Cell::Haml, or Cell::Slim
end

Namespaces

Cells can be namespaced as well.

module Admin
  class CommentCell < Cell::ViewModel

Invocation in Rails would happen as follows.

cell("admin/comment", @comment).()

Views will be searched in app/cells/admin/comment per default.

Rails Helper API

Even in a non-Rails environment, Cells provides the Rails view API and allows using all Rails helpers.

You have to include all helper modules into your cell class. You can then use link_to, simple_form_for or whatever you feel like.

class CommentCell < Cell::ViewModel
  include ActionView::Helpers::UrlHelper
  include ActionView::Helpers::CaptureHelper

  def author_link
    content_tag :div, link_to(author.name, author)
  end

As always, you can use helpers in cells and in views.

You might run into problems with wrong escaping or missing URL helpers. This is not Cells' fault but Rails suboptimal way of implementing and interfacing their helpers. Please open the actionview gem helper code and try figuring out the problem yourself before bombarding us with issues because helper xyz doesn't work.

View Paths

In Rails, the view path is automatically set to app/cells/ or app/concepts/. You can append or set view paths by using ::view_paths. Of course, this works in any Ruby environment.

class CommentCell < Cell::ViewModel
  self.view_paths = "lib/views"
end

Asset Packaging

Cells can easily ship with their own JavaScript, CSS and more and be part of Rails' asset pipeline. Bundling assets into a cell allows you to implement super encapsulated widgets that are stand-alone. Asset pipeline is documented here.

Render API

Unlike Rails, the #render method only provides a handful of options you gotta learn.

def show
  render
end

Without options, this will render the state name, e.g. show.erb.

You can provide a view name manually. The following calls are identical.

render :index
render view: :index

If you need locals, pass them to #render.

render locals: {style: "border: solid;"}

Layouts

Every view can be wrapped by a layout. Either pass it when rendering.

render layout: :default

Or configure it on the class-level.

class CommentCell < Cell::ViewModel
  layout :default

The layout is treated as a view and will be searched in the same directories.

Nested Cells

Cells love to render. You can render as many views as you need in a cell state or view.

<%= render :index %>

The #render method really just returns the rendered template string, allowing you all kind of modification.

def show
  render + render(:additional)
end

You can even render other cells within a cell using the exact same API.

def about
  cell(:profile, model.author).()
end

This works both in cell views and on the instance, in states.

View Inheritance

You can not only inherit code across cell classes, but also views. This is extremely helpful if you want to override parts of your UI, only. It's documented here.

Collections

In order to render collections, Cells comes with a shortcut.

comments = Comment.all #=> three comments.
cell(:comment, collection: comments).()

This will invoke cell(:comment, comment).() three times and concatenate the rendered output automatically.

Learn more about collections here.

Builder

Builders allow instantiating different cell classes for different models and options. They introduce polymorphism into cells.

class CommentCell < Cell::ViewModel
  include ::Cell::Builder

  builds do |model, options|
    case model
    when Post; PostCell
    when Comment; CommentCell
    end
  end

The #cell helper takes care of instantiating the right cell class for you.

cell(:comment, Post.find(1)) #=> creates a PostCell.

Learn more about builders here.

Caching

For every cell class you can define caching per state. Without any configuration the cell will run and render the state once. In following invocations, the cached fragment is returned.

class CommentCell < Cell::ViewModel
  cache :show
  # ..
end

The ::cache method will forward options to the caching engine.

cache :show, expires_in: 10.minutes

You can also compute your own cache key, use dynamic keys, cache tags, and conditionals using :if. Caching is documented here and in chapter 8 of the Trailblazer book.

The Book

Cells is part of the Trailblazer project. Please buy my book to support the development and to learn all the cool stuff about Cells. The book discusses many use cases of Cells.

![](https://raw.githubusercontent.com/apotonick/trailblazer/master/doc/trb.jpg)
  • Basic view models, replacing helpers, and how to structure your view into cell components (chapter 2 and 4).
  • Advanced Cells API (chapter 4 and 6).
  • Testing Cells (chapter 4 and 6).
  • Cells Pagination with AJAX (chapter 6).
  • View Caching and Expiring (chapter 8).

The book picks up where the README leaves off. Go grab a copy and support us - it talks about object- and view design and covers all aspects of the API.

This is not Cells 3.x!

Temporary note: This is the README and API for Cells 4. Many things have improved. If you want to upgrade, follow this guide. When in trouble, join the Zulip channel.

LICENSE

Copyright (c) 2007-2020, Nick Sutterer

Copyright (c) 2007-2008, Solide ICT by Peter Bex and Bob Leers

Released under the MIT License.

cells's People

Contributors

amatsuda avatar apotonick avatar c-lliope avatar calas avatar cameel avatar docwhat avatar drogus avatar frans-k avatar george-carlin avatar grimen avatar iazel avatar jlogsdon avatar joecorcoran avatar juniorz avatar kuraga avatar mjtko avatar olleolleolle avatar orien avatar paneq avatar petergoldstein avatar pikachuexe avatar richardboehme avatar robyurkowski avatar scharrels avatar seuros avatar smathy avatar sps196 avatar timoschilling avatar wingrunr21 avatar yogeshjain999 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cells's Issues

Are instance variables in cells overridden ?

I have noticed that instance variables in cells are overridden
by those in the controllers of the same name while the cell is
being rendered from the template (although the variables in the cell
are used if the cell method returns string directly). Is this
the intended behavior? I think it would be better the
variables defined in cells are on the top.
The patch attached will make it so.

diff --git a/lib/cell/base.rb b/lib/cell/base.rb
index 26720b0..6f7ea95 100755
--- a/lib/cell/base.rb
+++ b/lib/cell/base.rb
@@ -195,7 +195,9 @@ module Cell
     def render_view_for_state(state)
       ### DISCUSS: create Cell::View directly? are there still problematic class vars in View::Base
       view_class  = Class.new(Cell::View)
-      action_view = view_class.new(@@view_paths, {}, @controller)
+      controller = @controller.dup
+      clone_ivars_to(controller)
+      action_view = view_class.new(@@view_paths, {}, controller)
       action_view.cell = self
       ### FIXME/DISCUSS:
       action_view.template_format = :html # otherwise it's set to :js in AJAX context!

can't render a cell without a controller

I need to render a cell outside of a controller but it fails due to ActionView calling delegated methods that don't really exist. This patch (and the subsequent test case) fix the problem.

patch: 79aa612

'uninitialized constant Cell::TestCase' when running auto-generated tests in Rails 3.1.0.rc5

In cells 3.6.4 running rake test:cells fails with the following message:

/tmp/cells-test/test/cells/comment_cell_test.rb:3:in `<top (required)>': uninitialized constant Cell::TestCase (NameError)

Stack trace does not show anything interesting (every line points at rake-0.9.2/lib/rake/rake_test_loader.rb:9).

It happens even in a newly created rails app with nothing but a single cell. Happens with both cells 3.6.3 and 3.6.4 but not 3.6.2. Tested with ruby 1.9.2-p290, rails 3.1.0.rc5.

To reproduce:

  1. rails new cells-test
  2. Put gem 'cells', '>= 3.6.3' somewhere in Gemfile
  3. bundle install
  4. rails g cell Comment display
  5. rake test:cells

Also when I start irb and type

require 'cells'

I get

NameError: uninitialized constant Cell::Rails::ActionController   

[Rails 2.3] generate cell crashes (undefined method 'class_name')

 C:\projects\dmh>ruby script\generate cell TeaserBoxes become_a_merchant newsletter
  create  app/cells/
  create  app/cells/teaser_boxes
  create  test/cells
  create  app/cells/teaser_boxes_cell.rb
 undefined local variable or method `class_name' for #<CellGenerator:0x6123378>

ruby 1.8.6 (2010-02-04 patchlevel 398) [i386-mingw32]
cells (3.3.5)
rails (2.3.8)

The cell and the folder named after the cell stays empty.

Greets,
Christian

Missing template after migration and upgrade to cells 3.3.4

I am migrating a development site to a staging server and upgraded to cells 3.3.4. Now I am getting this error: "Missing template design/top.erb in view path app/cells:app/cells/layouts"
There have been no changes to the (relative) file locations but it appears from the stack trace that this file (top.html.erb) can't be found now.
Any thoughts?

render :nothing broken

I am using cells 3.5.5, Ruby 1.9.2p0, and Rails 3.0.4
Anytime I try to render :nothing, I get this error:
Template is missing

Missing layout layouts/insights with {:handlers=>[:erb, :rjs, :builder, :rhtml, :rxml, :haml], :formats=>[:html], :locale=>[:en, :en]} in view paths "/project/app/views", etc.

The fix for me has been render :text => '', but that feels dirty.

ArgumentError: wrong number of arguments (1 for 0)

I got this error:

wrong number of arguments (1 for 0)

<%= render_cell :shared, :menu %>

vendor/bundle/ruby/1.8/gems/actionpack-3.0.9/lib/abstract_controller/rendering.rb:74:in initialize' vendor/bundle/ruby/1.8/gems/actionpack-3.0.9/lib/abstract_controller/rendering.rb:74:ininitialize'
vendor/bundle/ruby/1.8/gems/actionpack-3.0.9/lib/abstract_controller/layouts.rb:299:in initialize' vendor/bundle/ruby/1.8/gems/cells-3.6.3/lib/cell/rails.rb:53:ininitialize'
vendor/bundle/ruby/1.8/gems/cells-3.6.3/lib/cell.rb:28:in new' vendor/bundle/ruby/1.8/gems/cells-3.6.3/lib/cell.rb:28:increate_cell_for'
vendor/bundle/ruby/1.8/gems/cells-3.6.3/lib/cell.rb:18:in render_cell_for' vendor/bundle/ruby/1.8/gems/cells-3.6.3/lib/cells/rails.rb:53:inrender_cell'

My fix:
In file "lib/cell/rails.rb" replace line "super" to "super *args":

   def initialize(parent_controller, *args)
        super *args
        @parent_controller  = parent_controller
        setup_backwardibility(*args)
    end

thanks.

Render cell is very slow under production environment

Hi,

Many compliments for the great cells plugins !

I'm having a strange performance problem using render_cell.

My application is running on Rails 2.3.2/2.3.3 - Ruby 1.8.7 patch level 72 with MySQL db and below I show you what happens rendering 48 cells (only one has db access):

  1. running under mongrel development (script/server -e development) I have this results
    696 msec View: 441 Db: 24

  2. running under mongrel production (script/server -e production) I have this results
    4352 msec View: 4293 Db: 35

The problem is clearly on view processing...

If I try to put the application in production under passenger 2.2.4 I have the same performance problem.

I've tried to transform some calls from render_cell to render :partial and the performance problem has gone away.

I don't want to return to partial or render_component, can you help me with this strange behaviour ?

Gem unusable in Rails 3

Render cells throws an exception.

Wrong number of arguements (1 for 0)

The version of rails is 3.0.5 and the GEM version is 3.6.2

Accessing flash

Hi,

after some times I'm retrying to use Rails cells...

The first cell I've created contains some logic to present flash messages (flash[:notice] / flash[:alert]) using jquery with fancybox but seems that flash object cannot be accessed from cell:

undefined method `flash' for #CommonCell:0xa656ecc

Extracted source (around line #1):

1: <% if flash[:notice] || flash[:alert] -%>
2: <script type="text/javascript">
3: $(document).ready(function(){
4: message = ""

Is there any workaround to access flash object from cell ?

Many thanks.

Route to a cell?

Anyway we can add a route to render a cell action?
With rails 3's fancy new routing features, maybe something like:
match 'components/basket' => BasketCell.action(:index)

The reason i would want to do this is to either load the component using Ajax, or move the caching to Varnish or something.
Hoping cells would provide incredibly light controller actions that generate small amounts of html components which can be accessed by Varnish and cached at the edge proxies.

image_tag not working with rails 3

When I use image_tag in a cell view I've "can't convert nil into String" error

What is weird is the following code is working


    =image_tag("http://dummyimage.com/32x32/bb9d77/fff.png&text=Thumb")

but that one is not working


       =image_tag("default/missing_xsmall.png")

However using the exact same code in a rails view is working. Am I missing something ?

content_for

...which we discussed already: I think seamless support for this it's really needed.

autotest configuration

One of the things that interests me about using cells is that it offers better testing capabilities. I'd love to be able to use autotest with cells and I'm wondering if anyone can help.

Here's what I have so far in .autotest:

Autotest.add_hook :initialize do |autotest|
  autotest.add_mapping(/^app\/cells\/(.*)_cell\.rb$/) { |filename, _|
    filename
  }
  autotest.add_mapping(/^app\/cells\/(.*)_cell\.rb$/) { |_, m|
    ["test/cells/#{m[1]}_test.rb"]
  }
end

Can anyone help ?

Nested Resources + cells + link_to = breakage.

I seem to be having a rather strange issue with nested resources. If i link to a child resource (example: link_to "New Store", :controller => "stores", :action => "new") from a cell being rendered by said child resource, i get an error saying the route can't be found. If i take that same link_to and cut/paste it directly into the page, it works fine. (paths work the same way.)

if i do a rake routes i can confirm the route is there.

Is there a workaround for this?

Deprecation Warnings: @options is deprecated!

Hi,

I keep getting these deprection warnings:

DEPRECATION WARNING: @options is deprecated! Call options.[] instead of @options.[]. Args: [:char].

It's not clear to me, how to avoid them. I've tried to call a method opts inststead of the variable @opts, but that didn't work.

What am I missing?

Greetings

Michael Kastner

Rails3 RC - Undefined method 'returning'

Hello,

I got an error using cell with Rails3 RC. It used to work fine with Rails3 beta 4.

Now I get this error :

ActionView::Template::Error (undefined method `returning' for #NavigationCell:0x2ffc920): 7: 8: - content_for :sidenav do 9: = render_cell :navigation, :tree, :type => :product, :cache_name => "product_simple"

Full gist here : http://gist.github.com/493733

Does anybody have this error too ?

Thank you !

url_for causes error in cell view.

Any ideas what's going on here?

test_select_list_with_selection(ContactCellTest):
ActionView::TemplateError: undefined method `rewrite' for nil:NilClass
On line #16 of app/cells/contact/select_list.html.erb


13:     end
14: %>
15:
16: <%= url_for(:controller => 'projects', :action => 'invoice') %>
17:
18: 
19:     >-


app/cells/contact/select_list.html.erb:16
app/cells/contact_cell.rb:32:in `select_list'
/test/cells/contact_cell_test.rb:42:in `test_select_list_with_selection'
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/testsuite.rb:34:in `run'
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/testsuite.rb:33:in `each'
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/testsuite.rb:33:in `run'
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/testsuite.rb:34:in `run'
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/testsuite.rb:33:in `each'
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/testsuite.rb:33:in `run'
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/ui/testrunnermediator.rb:46:in `run_suite'
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/ui/console/testrunner.rb:67:in `start_mediator'
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/ui/console/testrunner.rb:41:in `start'
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/ui/testrunnerutilities.rb:29:in `run'
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/autorunner.rb:216:in `run'
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/autorunner.rb:12:in `run'
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit.rb:278
-e:2

Add Travis CI

This is becoming a very good best practice for Ruby projects now, and it very much makes sense to ensure libs works with all rubies. Adding this is a matter of adding a YAML-file to the root and sign up at travis-ci.org, so I really suggest to do this to ensure quality of Cells gem. :)

cheers

link_to broken path when relative url root is set

Hi,
I have a rails app with your great cells gem, with ENV['RAILS_RELATIVE_URL_ROOT'] set.
While upgrading in rails 3, I noticed that all link_to rendered from cell views miss the relative path.
It appears that :script_name option doesn't get propagated as it happens in standard views.
Can you check if it is a bug or I'm missing sth?

Deprecation warnings for 3.3.5 on Rails 2.3.12

Hi there, I'm getting the following deprecation warnings as per the title of this issue:

DEPRECATION WARNING: ActiveSupport::Dependencies.load_paths is deprecated, please use autoload_paths instead. (called from evaluate_init_rb at /ree-1.8.7-2011.03@/gems/cells-3.3.5/rails/init.rb:19)
DEPRECATION WARNING: ActiveSupport::Dependencies.load_once_paths is deprecated and removed in Rails 3, please use autoload_once_paths instead. (called from evaluate_init_rb at /ree-1.8.7-2011.03@/gems/cells-3.3.5/rails/init.rb:23)

I've removed paths specific to my app from the above just in case they look funny :)

Is it possible to regress this back to the 3.3 branch?

#invoke throws ArgumentError: wrong number of arguments (0 for 1)

I'm just getting into cells and am really liking them but I'm having some issues with tests:

I have a PageCell with a :footer state which takes a single args parameter. On a call to invoke(:footer, :foo => 'bar') my code is throwing an unexpected ArgumentError: wrong number of arguments (0 for 1) exception.

I've just cloned the repo to try and get to the bottom of it, but running the gem's tests is resulting in a load of failing tests too, mostly NameError: uncaught throw 'invalid_test'.

Couldn't find 'cell' generator error on Rails 2.3.x

I'm using Rails 2.3.x with my project configured for Bundler support. I added gem 'cells' and ran rvm exec bundle install. Firstly it incorrectly installed cells 3.4.2 even though the Gemfile requires Rails 3.0.0. I'm not sure whether that's an issue with cells or Bundler. Anyway, I fixed it to gem 'cells', '~> 3.3.5', and got the version compatible with Rails 2.3.x, but the generator didn't work:

$ rvm ruby ./script/generate cell
Couldn't find 'cell' generator

even though this file exists:

/usr/local/rvm/gems/ruby-1.8.7-p302/gems/cells-3.3.5/rails_generators/cell/cell_generator.rb

So I'm stuck on square one :-(

Deprecation warning under Rails 2.3.11 and Cells 3.3.5

As encouraged by Rails-Core developers, upgrade to latest version of Rails 2.3 was recommended.

Once I've upgraded, application started to show the following warning:

DEPRECATION WARNING: ActiveSupport::Dependencies.load_paths is deprecated, please use autoload_paths instead. (called from evaluate_init_rb at /Users/luis/.rvm/gems/ruby-1.8.7-p330@krrb/gems/cells-3.3.5/rails/init.rb:8)

https://github.com/apotonick/cells/blob/rails-2.3/rails/init.rb#L8

That is because load_paths is now called autoload_paths

Checking for ActiveSupport::Dependencies.respond_to?(:autoload_paths) can provide a working solution for both newer and older Rails versions.

Thank you.

Generator ignores --haml option

$ rails g cell Opinion display --haml
create app/cells/opinion_cell.rb
invoke erb
create app/cells/opinion/display.html.erb
invoke rspec
create spec/cells/opinion_cell_spec.rb

The .erb file created is the standard one:
cat app/cells/opinion/display.html.erb


Opinion#display

<p>
  Find me in app/cells/opinion/display.html.erb
</p

Cell rendered even if before_filter renders earlier

In controller class if a before filter renders or redirects, the action will not run. However it doesn't work the same for cells.

Following code should render "filter", and renders "cell"

class SamleCell < Cell::Rails
  before_filter :test5

  def sample
    render :text => "cell"
  end

  private
    def test5
      render :text => "filter"
    end
end

Tested in rails3.

Cells breaks asset precompilation in Rails 3.1.0.rc

Cells in its Railtie wants its initializers to be executed after :set_routes_preloader. I think this is a bad idea since Finisher is expected to run last. Its :finisher_hook executes :after_initialize hooks and many of them assume that initialization has already been performed. While Rails does not prevent you from doing this it was probably not expected - it causes :finisher_hook to be pushed too far down in initialization order and makes asset precompilation fail.

I think that Cells' initializers should be converted into :after_initialization hooks.

See the following links for more details:
Rails issue #1587: after_initialize hooks sometimes get executed during initialization
Rails pull request #1602: Do not TSort Finisher and Bootstrap initializers

UrlFor, UrlHelpers and subdomains

Hey, I've been trying to get Cells to render a menu that links to a list of sub-domains.

I have gone through @wingrunr21's recent pull request for adding the UrlFor module, but I'm unsure how one should go about getting this working.

My cell looks like this:

class MenuCell < Cell::Rails

    include ActionController::UrlFor
    include UrlHelper


    def primary
        render
    end
 end

But I have also tried this method too:

module UrlHelper

    def with_subdomain( subdomain )
        subdomain = ( subdomain || '' )
        subdomain += '.' unless subdomain.empty?
        [subdomain, request.domain, request.port_string].join
    end


    def url_for( options = nil )
        if options.kind_of?( Hash ) && options.has_key?( :subdomain )
            options[:host] = with_subdomain( options.delete( :subdomain ) )
        end

        super
    end

end


module Cell
    class Rails < AbstractController::Base
        include ActionController::UrlFor
        include UrlHelper
    end
end

Ideally I think Cells should be able to handle a link_to call like this:

%li= link_to mod.name, root_url { :subdomain => mod.subdomain }

Do you know what needs to be done here?

rspec ?

rails g cell says :

rails g cell main_menu display sort -e haml -t rspec
...
Spec:
  spec/cells/main_menu_cell_spec.rb

but :

$ rails g cell main_menu display sort -e haml -t rspec
  create  app/cells/main_menu_cell.rb
  invoke  haml
  create    app/cells/main_menu/display.html.haml
  create    app/cells/main_menu/sort.html.haml
   error  rspec [not found]

Cells::Rails::ActionController methods not available in ActionController::Caching::Sweeper

Given this sweeper:

class UserSweeper < ActionController::Caching::Sweeper
  observe User

  def after_update(user)
    Rails.logger.debug Rails.cache.instance_variable_get(:@data).keys.inspect
    expire_cell_state HeaderCell, :show
    Rails.logger.debug Rails.cache.instance_variable_get(:@data).keys.inspect
  end

end

when #after_update is called the HeaderCell cache key isn't being deleted as expected. No errors are raised.

Firing up the debugger reveals that we are hitting ActionController::Caching::Sweeping#method_missing with @controller equal to nil and so being silently returned.

A simple include Cells::Rails::ActionController in the Sweeper fixes this but I'm left wondering why it's not being properly mixed in without this.

ree-1.8.7-2011.03, rails 3.0.9, cells 3.6.4.

Calling cached cell writes nothing to log file

I'm not sure if this is by design or not but I was expecting that when caching is configured for a cell, that details of cache hits, misses and deletions would be written to the log file (at least in development).

Is this something that is broken, intentionally missing or just as yet, not implemented and would be accepted as a patch?

3.6.1 gemspec problem

Hi,

Seems like the github repo has :

  s.add_dependency "actionpack",  "~> 3.0"
  s.add_dependency "railties",    "~> 3.0"

but the gem has :

  s.add_dependency "actionpack",  "~> 3.0.0"
  s.add_dependency "railties",    "~> 3.0.0"

helpers defined in controllers are not accessible from cells

In Application-controller:

helper_method :current_account

In cell:

class LayoutCell < Cell::Base
  helper :layout, :navigation
  # helper_method :current_account # don't seem to affect the error

  def header
    render
  end
  def footer
    render
  end
end

The error:

undefined method `current_account' for #

Accessing Devise Helper methods inside cell controllers and views

Hi,

I am using Devise as authentication plugin. Since login box is common
across all my pages, I have extracted that out as a cell. However, I
am getting errors while accessing devise helper methods such as
user_signed_in? etc. It is giving me undefined method error. Based on
the last post, I tried inserting "include
Devise::Controllers::Helpers". It still is giving me errors.
Here's the cell controller and the view code

app/cells/authenticate_cell.rb

class AuthenticateCell < Cell::Rails 
    include Devise::Controllers::Helpers 
    def login 
      @user = User.new 
      render 
    end 
end 

app/cells/authenticate/login.html.rb

<div class="container login_info"> 
  <% if user_signed_in? %> 
    Signed in as <%= current_user.email %>. Not you? 
    <%= link_to "Sign out", destroy_user_session_path %> 
  <% else %> 
  <%= form_for(resource, :as => resource_name, :url => 
session_path(resource_name)) do |f| %> 
    <p><%= f.label :email %><br /> 
    <%= f.email_field :email %></p> 
    <p><%= f.label :password %><br /> 
    <%= f.password_field :password %></p> 
    <% if devise_mapping.rememberable? -%> 
      <p><%= f.check_box :remember_me %> <%= f.label :remember_me %></ 
p> 
    <% end -%> 
    <p><%= f.submit "Sign in" %></p> 
    <% end %> 
  <% end %> 
</div> 

Thanks in advance.

link_to and url_helper method problem in Cells views

Using Rails 3.0.3 and the latest version of cells.

The following HAML is breaking the view:

  • if @group.user
    =link_to @group.user.name , @group.user

With the error:
undefined method `user_path' for Cell::Rails::View

Is there some special way to get these url_helpers into Cells views?
Or am I missing something?

layout class macro not working

hello guys. I'm moving my first steps in cells because we decided to use it in our next project at work. I have defined a basic layout in app/cells/layouts/main_cell.html.erb. When I pick the layout from the render method it works, but when I call the layout class method it doesn't. Is this intended?

Here is an explanatory example:

class NewsCell < Cell::Rails
  layout "main_cell"

  def spotlight
    render :layout => "main_cell" # renders with the correct layout
  end

  def more_news
    render # doesn't render the correct cell layout
  end

end

I'm using Rails3.1 with Cells 3.6.2.

Thank you for your time.

Issues with form processing flow

As it can be seen at https://github.com/apotonick/cells_examples/blob/master/app/cells/newsletter_cell.rb (I couldn't find any other example for processing forms in cells), it is suggested to use one cell for both "new" and "create" actions, however there at least 2 issues with this way:

Let's imagine we have "new comment" cell (with actual form) embedded under blog post. Once user submits form:

  1. After comment is saved, visitor is not redirected, so after he hits browsers's refresh button, he submits comment again. With controllers you would simply redirect, and it won't happen.
  2. As comment cell uses POST request, you have to define appropriate route to blog post, so blog post is displayed, and only then "new comment" cell is rendered and processed (form/model validated and added or errors returned).

Cell class uninitialized in threadsafe mode!

uninitialized constant CommentsCell

Extracted source (around line #122):
119: <% end %>
120:
121:


122: <%= render_cell :comments,:index, :commentable_type => "PlaceArticle", :commentable_id => @article.id %>
123:

124:

E:/ruby/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/dependencies.rb:92:in const_missing' E:/ruby/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/inflector.rb:361:inconstantize'
E:/ruby/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/inflector.rb:360:in each' E:/ruby/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/inflector.rb:360:inconstantize'
E:/ruby/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/core_ext/string/inflections.rb:162:in constantize' D:/work/ongoup/vendor/plugins/cells/lib/cell/base.rb:320:inclass_from_cell_name'
D:/work/ongoup/vendor/plugins/cells/lib/cell/base.rb:360:in create_cell_for' D:/work/ongoup/vendor/plugins/cells/lib/rails_extensions.rb:30:inrender_cell'
D:/work/ongoup/app/views/wiki/articles/show.html.erb:122:in _run_erb_app47views47wiki47articles47show46html46erb' D:/work/ongoup/app/controllers/wiki/articles_controller.rb:36:inindex'

I was turn on the threadsafe in the environments/production.rb

How do I…prepend a view path for cells like with Rails’ prepend_view_path?

From https://github.com/apotonick/cells/wiki/Troubleshooting

I tried adding this initialiser but I get an error from line 7 of actionpack-3.0.3/lib/action_view/paths.rb:

can't modify frozen array

It seems that Cell::Base.view_paths is no longer an array but a ActionView::PathSet object.

If it helps, I'm actually trying to use cells within a gem (I'm breaking a complex application in to gems so we can build new sites from those parts) - but neither an initializer block in the Gem/Engine works nor an a initializer file within the main app.

Any ideas?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.