Reference YAML Node using method parameter - ruby

I load a yaml, and need to define a scope for it, to reference a specific node.
myYaml = YAML.load_file('myfile.yml').with_indifferent_access
Normally, I can just do
myYaml[:first_node][:first_child][:second_child]
However, I wanted to pass the path to a method to scope it for me. I am struggling to do something like this..
scope_path = [:first_node,:first_child,:second_child]
def scope(scope_path)
myYAML[scope_path]
end
# So I need code to convert my scope_path parameter to
myYaml[:first_node][:first_child][:second_child]

You can simple use Hash#dig:
myYaml.dig(:first_node, :first_child, :second_child)

Related

How to override node attribute value within ruby block / using a value of variable in ruby block?

I am using Chef of AWS OpsWorks. I have a custom attribute JSON like below;
{
"custom_attributes": {
"custom_attribute_1": "default_value"
}
}
and, I can use #{node[:custom_attributes][:custom_attribute_1]}" to print / use that value anywhere in my recipes. Then, I want to change that value and I can achieve it by mentioning it in default.rb file inside attributes directory of my cookbook, like below;
override['custom_attributes']['custom_attribute_1'] = "overridden_value"
Now, if I print / use this attribute, new value will get reflected. This works well.
Lets consider I haven't overridden the value and trying to use a ruby block for this like below;
ruby_block 'test_block' do
block do
node.override['custom_attributes']['custom_attribute_1'] = "overridden_value"
end
action :run
end
log 'message' do
message "attribute value = #{node[:custom_attributes][:custom_attribute_1]}"
level :info
end
Now, if we take a look at log, it will show default_value instead of overridden_value. If my understanding is clear, its happening because of compile and convergence phases. Can somebody show me how to fix this issue?
Thanks.
EDIT
As per my research, I understand that the attribute assignment is happening at compile phase and ruby block evaluation is happening at converge phase. In that case, can somebody show me how to override / create new attribute using Chef Lazy? Below is a blog I came across;
https://blog.alanthatcher.io/lazy-is-good/
can somebody show me how to override / create new attribute using Chef Lazy?
you can use lazy evaluation
In some cases, the value for a property cannot be known until the execution phase of a Chef Infra Client run. In this situation, using lazy evaluation of property values can be helpful. Instead of a property being assigned a value, it may instead be assigned a code block. The syntax for using lazy evaluation is as follows:
property_name lazy { code_block }
where lazy is used to tell Chef Infra Client to evaluate the contents of the code block later on in the resource evaluation process (instead of immediately) and { code_block } is arbitrary Ruby code that provides the value.
so you might want to use lazy as follows
log 'message' do
message lazy { "attribute value = #{node[:custom_attributes][:custom_attribute_1]}" }
level :info
end

How can I call a Chef resource from an HWRP?

Maybe this is really simple, and I'm just not understanding something. I want to invoke a Chef resource from within an HWRP that I wrote. In my scenario, I'd like to invoke the reboot resource. How should I go about doing so?
I have tried something like the following:
def reboot_system
wu_reboot = Chef::Resource::Reboot.new('wu_reboot', :reboot_now)
wu_reboot.run_action(:reboot_now)
end
A few things. I am not sure if I should be creating an instance of Chef::Resource::Reboot or Chef::Provider::Reboot. I also don't really understand the second argument listed above..this is supposed to be the "run_context", but I don't know what that is. Finally, I do not know how to set attributes or invoke an action.
I tried using this as a format to go by, but I haven't been able to get it to work so far. Any help understanding would be much appreciated.
EDIT:
I looked at the source code and I could just execute this:
node.run_context.request_reboot(
:delay_mins => #new_resource.delay_mins,
:reason => #new_resource.reason,
:timestamp => Time.now,
:requested_by => #new_resource.name
)
However, I don't think this is the best solution. I would like to know how to accomplish invoking the resource instead of bypassing it this way.
You can find an example of using Chef-Resources inside a HWRP in an older revision of the official Jenkins cookbook (was converted to LWRP in the meantime):
https://github.com/opscode-cookbooks/jenkins/blob/v2.0.2/libraries/plugin.rb#L138-L141
Keep in mind, that the Reboot resource is rather new (Chef 12+)
You can do it the same way you would in a recipe. If you need it to run immediately, then you would do:
reboot 'now' do
action :nothing
end.run_action(:reboot_now)
Within Ruby classes, you don't have access to the Chef DSL, so you have to access the underlying implementation of the resource as a class. The name of the class will be the camelcase-conversion of the resource name. You invoke the action with the run_action method.
Your original version actually was pretty close. You only use the resource, not the provider (because the provider may not even always be the same, depending on your platform).
The run_context is an object that chef uses to pass information to the resource - for instance, you can access node attributes through run_context.node['attributename']. It is already a member variable in your provider (and I think also in the resource object); you can simply pass it in to the constructor for your new resource.
You set attributes through member variables by the same name, and you trigger the actual action with the run_action method.
r = Chef::Resource::Reboot.new("wu_reboot", run_context)
r.reason("Because we need a reboot")
r.run_action(:reboot_now)

How to pass variable to DB.from in Sequel?

I'm just starting to use Sequel in Ruby, and like it alot.
I want to pass a variable to the "from" method. So instead of calling a method like so:
DB.from(:items)
I'd like to call the method with a variable. For example:
# both of the following approaches fail
tableName = "items"
DB.from(tableName)
DB.from(:tableName)
But it fails with a sql error about a value that's not in my variable. I don't think this is a Sequel issue... I think it's a "I'm new to Ruby" issue.
How can I pass a variable to the from method above?
Do as below using String#to_sym method :
DB.from(tableName.to_sym)
Looking at the documentation of Sequel::Database#from, it seems it accepts all arguments as symbols. Thus you need to convert the string object pointed by the local variable tableName, to a symbol object.

PageObject with Ruby - set text in a text field only works in the main file

I'm automating a site that has a page with a list of options selected by a radio button. When selecting one of the radios, a text field and a select list are presented.
I created a file (test_contracting.rb) that is the one through which I execute the test (ruby test_contracting.rb) and some other classes to represent my page.
On my class ContractPage, I have the following element declaration:
checkbox(:option_sub_domain, :id => "option_sub_domain")
text_field(:domain, :id => "domain_text")
select_list(:tld, :id => "domain_tld")
I've created in the ContractPage a method that sets the configuration of the domain like this:
def configure_domain(config={})
check_option_sub_domain
domain = config[:domain]
tld = config[:tld]
end
When I call the method configure_domain from the test_contracting.rb, it selects the radio button, but it doesn't fill the field with the values. The params are getting into the method correctly. I've checked it using "puts". Even if I change the params to a general string like "bla" it doesnt work. The annoying point is that if on test_contracting.rb I call the exact same components, it works.
my_page_instance = ContractPage.new(browser)
my_page_instance.domain = "bla"
my_page_instance.tld = ".com"
What I found to work was to in the configure_domain method, implement the following:
domain_element.value = config[:domain]
tld_element.send_keys config[:locaweb_domain]
Then it worked.
The documentation for the PageObjects module that I'm using as reference can be found here: http://rubydoc.info/github/cheezy/page-object/master/PageObject/Accessors#select_list-instance_method
Do you guys have any explation on why the method auto generated by the pageobject to set the value of the object didnt work in this scope/context ?
By the way, a friend tried the same thing with Java and it failed as well.
In ruby all equals methods (methods that end with the = sign) need to have a receiver. Let me show you some code that will demonstrate why. Here is the code that sets a local variable to a value:
domain = "blah"
and here is the code that calls the domain= method:
domain = "blah"
In order for ruby to know that you are calling a method instead of setting a local variable you need to add a receiver. Simply change your method above to this and it will work:
def configure_domain(config={})
check_option_sub_domain
self.domain = config[:domain]
self.tld = config[:tld]
end
I'm pretty new to this world of Selenium and page objects but maybe one of my very recent discoveries might help you.
I found that that assignment methods for the select_list fields only worked for me once I started using "self" in front. This is what I have used to access it within my page object code. e.g., self.my_select_list="my select list value"
Another note - The send_keys workaround you mention is clever and might do the trick for a number of uses, but in my case the select list values are variable and may have several options starting with the same letter.
I hope something in here is useful to you.
UPDATE (Jan 3/12)
On diving further into the actual Ruby code for the page object I discovered that the select_list set is also using send_keys, so in actuality I still have the same limitation here as the one I noted using the send_keys workaround directly. sigh So much to learn, so little time!

Trouble creating custom routes in Ruby on Rails 3.1

I can't seem to set up a custom URL. All the RESTful routes work fine, but I can't figure out how to simply add /:unique_url to the existing routes, which I create in the model (a simple 4 character random string) and will serve as the "permalink" of sorts.
Routes.rb
resources :treks
match ':unique_url' => 'treks#mobile'
Controller
.
.
def mobile
#trek = trek.find(params[:id])
end
Is this because I'm trying to define a custom action on an existing resource? Can I not create custom methods on the same controller as one with a resource?
By the way, when I change routes.rb to match 'treks/:id/:unique_url' => treks#mobile it works fine, but I just want the url to simply be /:unique_url
Update It seems like find_by_[parameter] is the way to go...
I've been playing in console and I can't seem to get any methods to come forward...I can run Trek.last.fullname for example, but cannot run #trek = Trek.last...and then call...#trek.lastname for example. Any clues why? I think this is my issue.
So is there a field on Trek which stores its unique url? If so you should be doing something like this:
#trek = Trek.find_by_url(params[:unique_url])
trek.find_by_unique_url( params[:unique_url] ) # should do the trick
#pruett no, the find_by_XXX methods are generated on-the-fly via Ruby's method_missing call! So instead of XXX you can use any of the attributes which you defined in a model.
You can even go as far as listing multiple attributes, such as:
find_by_name_and_unique_url( the_name, the_unigue_url)
Check these pages:
http://guides.rubyonrails.org/active_record_querying.html
http://m.onkey.org/active-record-query-interface
if you get a undefined method ... for nil:NilClass , it means that the object you are trying to call that method on does not exist, e.g. is nil.
You probably just missed to put an if-statement before that line to make sure the object is non-nil
Hmm. I usually would do something like this:
map.connect "/:unique_url", :controller => "treks", :action => "mobile"
Then in that controller the ID isn't going to be applicable.. you'd need to change it to something like this:
def mobile
#trek = trek.find_by_unique_url(params[:unique_url])
end
(that's if unique_url is the column to search under)

Resources