activerecord - Rails - group_by -


my application has few reports , i'm trying make helper method group_by these collections.

example:

def group_collection(collection, options = {})     column = options[:column]     group_count = collection.group_by{ |item| item.column.strftime('%b %y')} end 

this how plan use it

@user_groups = group_collection(@users, :column => "created_at") 

unfortunately, not work.

undefined method `column' for... [collectionobject] 

any clues on how make "column" variable actual column type @ runtime considers activerecord column , not instance method?

ignoring of other problems in code, trying column can done so:

collection.group_by { |item| item.send(column).strftime('%b %y') } 

this works because in ruby way access instance variables through accessor methods, named after variable you're trying access, @item.foobar calls foobar method on @item.

now, "other problems". it's great you're trying move repeated behavior single place, , shows you're thinking extensibility when make things less explicit in favor of being flexible. however, there couple of things aren't going work out here feel compelled point out.

  1. grouping works on lots of data types, of don't respond strftime. hard coding call you're introducing unexpected behavior means can't run group_collection(@users, :column => 'phone_number'). instead, run after testing column data can respond it.

    collection.group_by |item|   data = item.send(column)   data.respond_to?(:strftime) ? data.strftime('%b %y') : data end 
  2. if nail down behavior of helper method group on arbitrary column, can ditch additional complexity of accepting options hash, circumvent it.

    def group_by_column(collection, column)   collection.group_by { ... } end group_by_column(@users, :column) 
  3. you can group arbitrary column more easily, provided you're using ruby 1.9+ , don't need additional formatting..

    @users.group_by &:created_at 

Comments

Popular posts from this blog

python - Scipy curvefit RuntimeError:Optimal parameters not found: Number of calls to function has reached maxfev = 1000 -

c# - How to add a new treeview at the selected node? -

java - netbeans "Please wait - classpath scanning in progress..." -