Rails how to access a hash in model from console - ruby-on-rails-4

Using Rails 4. I have a hash in a model and I'd like to be able to access it via the rails console for testing some code. How do I do this?
foo = {'one' => 'ONE', 'two' => 'TWO'}
I've tried the following, but it gives me an "undefined method 'foo' in class..."
ModelName.foo['one']
Thanks for helping.

Are you trying to use foo as a constant? If so, you can set it and then reference it as:
class ModelName
FOO = {'one' => 'ONE', 'two' => 'TWO'}
end
ModelName::FOO['one']
An alternative to keep the reference as you have it:
class ModelName
def self.foo
{'one' => 'ONE', 'two' => 'TWO'}
end
end

Related

CakePHP - Router::url doesn't build pretty URLs when there's a regex match in the Router::connect

In my CakePHP, my routes.php file looks like this:
Router::connect('/premios/:category',
array('controller' => 'prizes', 'action' => 'category'),
array(
'category' => '\bmarcas|restaurantes|combustibles|peluqueria\b',
));
This way whenever a user enters the /premios url, the next parameter is matched with the "category" regex. This works perfect.
The problem is that when I want to generate a pretty url for the category, let's say, "peluqueria", using this line of code generates a "non-pretty" url:
Router::url(array('controller' => 'prizes', 'action' => 'category', 'peluqueria')); ?>
Instead of generating a pretty URL (/premios/peluqueria) it generates a non pretty url (/prizes/category/peluqueria).
What am I doing wrong? Or is this a limitation of the Router::url function?
A workaround would be to define every connect, avoiding the regex, but it isn't a pretty as the current solution plus it would get annoying when the categories count start to grow.
Any ideas?
You have to actually name the category parameter in Router::url, like this
Router::url(array('controller' => 'prizes',
'action' => 'category',
'category' => 'peluqueria'));
And you'd probably want to pass that "category" parameter to the category action in Prizes, so you're missing something
Router::connect(
'/premios/:category',
array('controller' => 'prizes', 'action' => 'category'),
array(
'pass' => array('category'),
'category' => '\bmarcas|restaurantes|combustibles|peluqueria\b'
)
);
Look this part of the docs with more detention :)

How to set the default selected value for a Doctrine ObjectRadio element

I've got a simple user registration form where a user can choose their own user type. The user type maps to a role. This is part of a zf2 application using the doctrine2 module.
The relevant part of the init() method of my user fieldset looks like this:
public function init()
{
// ... other field definitions ...
$roleRadio = new ObjectRadio('role');
$roleRadio->setLabel('What type of user are you?')
->setOptions(
array(
'object_manager' => $this->objectManager,
'target_class' => 'MyUser\Entity\Role',
'property' => 'roleId',
'is_method' => true,
'find_method' => array(
'name' => 'findBy',
'params' => array(
'criteria' => array('userselectable' => true),
'orderBy' => array('displayorder' => 'ASC'),
),
),
)
);
$this->add($roleRadio);
// ... more stuff ...
}
I'm using Doctrine's ObjectRadio class for this element to automatically populate the value options. Is there any way to set the default selected value?
I know I can just do something like this:
$form->get('user')->get('role')->setValue(3);
But I don't want to hard code this and I also don't want to put that kind of logic in my controller.
Any suggestions?
I don't know what do you mean by "I don't want to hard code this", but you can do it as you said in your controller, or you can do it in the form definition by setting attributes as the following:
$roleRadio->setAttributes(array('value' => 3));

How to get all associations for a model

Is there any way in rails to get a list of all associated models for a given model?
I'm thinking in something like:
post_associations = Post.associations()
Thanks.
Post.reflections
#=> { :author => #<ActiveRecord::Reflection::AssociationReflection:0x0...>,
:comments => #<ActiveRecord::Reflection::AssociationReflection:0x0...> }
Post.reflections.keys
#=> [:author, :comments]

Custom Prestashop Admin Module

I am developing a module for prestashop (basically, it's a very custom import of data and the only thing I need is to have a form and process data). I have created controller class derived from the ModuleAdminController but the problem is where should I put the tpl file containing the look of my custom form?
I realize that I can put tpl file to the templates but I want to keep all files within my module folder, is it possible (probably somewhere like "/views/templates/admin")?
This is the most easy method to create a basic admin controller / action in Prestashop 1.6
Create basic configuration :
./config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<module>
<name>foo</name>
<displayName><![CDATA[Foo]]></displayName>
<version><![CDATA[2.1.3]]></version>
<description><![CDATA[Bar.]]></description>
<author><![CDATA[your-name]]></author>
<tab><![CDATA[administration]]></tab>
<is_configurable>0</is_configurable>
<need_instance>0</need_instance>
<limited_countries></limited_countries>
</module>
./foo.php
if (!defined('_PS_VERSION_'))
exit;
class BarcodeEasyPrint extends Module
{
public function __construct()
{
$this->name = 'foo';
$this->tab = 'administration';
$this->version = '1.0.0';
$this->author = 'your-name-here';
$this->need_instance = 0;
$this->bootstrap = true;
parent::__construct();
$this->displayName = $this->l('Foo');
$this->description = $this->l('Bar.');
if ((int)Tools::getValue('p'))
$this->page = (int)Tools::getValue('p');
}
}
You need to create the controller with base functions :
./controllers/admin/AdminFooController.php
class AdminFooController extends ModuleAdminController {
public function __construct() {
$this->bootstrap = true;
parent::__construct();
}
public function createTemplate($tpl_name) {
if (file_exists($this->getTemplatePath() . $tpl_name) && $this->viewAccess())
return $this->context->smarty->createTemplate($this- >getTemplatePath() . $tpl_name, $this->context->smarty);
return parent::createTemplate($tpl_name);
}
public function initContent(){
parent::initContent();
$tpl = $this->createTemplate('content.tpl')->fetch();
/* DO STUFF HERE */
$posts = array();
$this->context->smarty->assign('posts', $posts);
}
}
You can use boostrap directly in the template file :
./views/templates/admin/content.tpl
<div class="row">
<div class="col-md-6">
</div>
<div class="col-md-6">
</div>
</div>
If it is an admin module only, then you will have no need to create any views. Because Prestashop provides a nice structure for admin section which is easy to use and we dont need to use any views or .tpl files. For admin section, normally three types of views or .tpl files are required, one for data display in grid, second for form and third for displaying a single record.
Prestashop already created .tpl files for them which you can find in "admin_folder/themes/default/templates". In our controllers for admin, for form and for data grid, we just create arrays and PS handles to view the form and data grid according to the arrays we created.
So if you need a custom form at admin, then create a public function renderForm and create the form array in it, like below:
$this->fields_form = array(
'legend' => array(
'title' => $this->l('Video'),
'image' => '../img/admin/tab-genders.gif'
),
'input' => array(
array(
'type' => 'text',
'label' => $this->l('Video Title:'),
'name' => 'title',
'lang' => true,
'size' => 70,
'hint' => $this->l('Invalid characters:').' 0-9!<>,;?=+()##"�{}_$%:',
'required' => true
),
array(
'type' => 'textarea',
'label' => $this->l('Video Code'),
'name' => 'video_code',
'rows' => 5,
'cols' => 70,
'desc' => $this->l('Place the embed code for the video')
),
),
'submit' => array(
'title' => $this->l('Save'),
'class' => 'button'
)
);
return parent::renderForm();
} /* End of render member */
For other fields, checkout other prestashop admin controllers and you will see that how easily we can create forms in PS using that simple definitions in the arrays and we dont need to create .tpl files.
For front end, we can use the new modules MVC structure, where our module folder have sub folders for controllers (controllers/front, controllers/admin) , views and models .
Hope this will help you.
Thank you
You need to use the helper form, here is the documentation for it, it is really easy to use ;) .
http://doc.prestashop.com/display/PS15/HelperForm
You also can find more information about how and where to use helper form, look for the function getContent() and displayForm().
http://doc.prestashop.com/display/PS15/Creating+a+PrestaShop+module
unfortunately any document not exist to point directly to solve this question but hear i have some URLs really useful and you should combine theme and get your realize:
http://presthemes.com/prestashop-news/modules-classes-and-controller-override-by-julien-breux-4.html
http://doc.prestashop.com/display/PS15/Diving+into+PrestaShop+Core+development
http://doc.prestashop.com/display/PS15/New+Developers+Features+In+PrestaShop+1.5
http://blog.belvg.com/how-to-implement-a-controller.html
best regards
extending the answer from #altafhussain create a folder views/templates/admin in your module and place your customview.tpl
Than append the free text block as below.
$this->fields_form = array(
'legend' => array(
'title' => $this->l('Legend')
),
'input' => array(
array(
'type' => 'free',
'label' => 'Whatever label text',
'desc' => $this->display(__FILE__,'views/templates/admin/customview.tpl'),
'name' => 'FREE_TEXT',
'required' => false
)
),
'submit' => array(
'title' => $this->l('Save'),
'class' => 'button'
)
);
return parent::renderForm();
}

Testing a model spec that uses an after_create callback

Here is a model that I'm using, I've simplified it a bit down to the simplest form that still fails my example:
class User < ActiveRecord::Base
after_create :setup_lists
def setup_lists
List.create(:user_id => self.id, :name => "current")
List.create(:user_id => self.id, :name => "master")
end
end
And I'd like to spec the example as follows:
require 'spec_helper'
describe User do
before(:each) do
#user = Factory(:user)
end
describe "#setup_lists" do
before(:each) do
List.stub(:create).with(:name => "current")
List.stub(:create).with(:name => "master")
it "creates a new master list" do
List.should_receive(:create).with(:name => "master")
end
it "creates a new current list" do
List.should_receive(:create).with(:name => "current")
end
end
end
Which I expected would work just fine, but I am left with the following error:
Failures:
1) User#setup_lists creates a new master list
Failure/Error: List.should_receive(:create).with(:name => "current")
(<List(id: integer, name: string, created_at: datetime, updated_at: datetime, user_id: integer) (class)>).create({:name=>"current"})
expected: 1 time
received: 0 times
# ./spec/models/user_spec.rb:44
2) User#setup_lists creates a new current list
Failure/Error: List.should_receive(:create).with(:name => "master")
(<List(id: integer, name: string, created_at: datetime, updated_at: datetime, user_id: integer) (class)>).create({:name=>"master"})
expected: 1 time
received: 0 times
# ./spec/models/user_spec.rb:48
Can anybody help me understand why this is happening?
Three issues:
1) The User object is created before setting the message expectation, so should_receive never gets to see the message;
2) You're stubbing out methods for which you're also setting expectations. You want to stub out methods for which you don't set expectations, but which are needed for the test to pass
3) You need to pass in all the parameters
To fix, create the User object after setting the expectaion, and stub out each method in turn (because your model calls List.create twice):
describe User do
describe "#setup_lists" do
it "creates a new master list" do
List.stub(:create).with(:user_id=>1,:name => "current")
List.should_receive(:create).with(:user_id=>1,:name => "master")
#user = User.create
end
it "creates a new current list" do
List.stub(:create).with(:user_id=>1,:name => "master")
List.should_receive(:create).with(:user_id=>1,:name => "current")
#user = User.create
end
end
end
While it's really an issue of style, it makes more sense to use a real User object here rather than a factory, since you're testing the model itself.
zetetic's answer is awesome, but if you want something a bit quicker (and still works), I'd recommend using the shoulda-callback-matchers gem. It's a complete set of matchers that make testing callbacks easier. I'm all about easy & reducing boilerplate. You can see some examples in my RSpec model testing skeleton if you care to look.
Either way gets the job done!