Mongoid Delete Document matching ID - ruby

I'm trying to remove a duplicate document in my collection. Here's my code:
class Sites
include Mongoid::Document
store_in collection: "sites"
end
Sites.destroy_all(conditions: { _id: BSON::ObjectId("5685a45be4b06ab5911dcd12")})
Here's what is returned:
D, [2015-12-31T17:39:16.488657 #10126] DEBUG -- : MONGODB | localhost:27017 | rails.find | STARTED | {"find"=>"sites", "filter"=>{"conditions"=>{"_id"=>BSON::ObjectId('5685a45be4b06ab5911dcd12')}}}
D, [2015-12-31T17:39:16.488946 #10126] DEBUG -- : MONGODB | localhost:27017 | rails.find | SUCCEEDED | 0.000189083s
But when I search the document is still there :(
{"_id"=>BSON::ObjectId('5685a45be4b06ab5911dcd12'), "name"=>"StackOverflow", "title"=>"Stack Overflow", "type"=>"Forum", "url"=>"http://www.stackoverflow.com"}
How do I permanently delete a document by reference using Mongoid?

Mongoid with 5.x follows a lot more closely to the AR methods we are used to so your id field is behaves in a similar way.
Sites.where(id: '5685a45be4b06ab5911dcd12').delete
To have all the necessary callbacks be called as well just use .destroy. Just know this loads everything into memory and can be expensive.
Sites.where(id: '5685a45be4b06ab5911dcd12').destroy

After doing a lot of iterations this works for me:
Sites.destroy_all({ :_id => BSON::ObjectId('5685a45be4b06ab5911dcd12')})
I've found that Mongoid is not very helpful when troubleshooting. I have to do a lot more trial and error to discover how to do things :(

Related

Fali to use getAppliedStereotype to get id and name of requirement

In Eclipse, Using Papyrus neon and Acceleo 3.7 for SysML 1.4 diagram, the getAppliedStereotype()returns null.
The modules are
[module generate('http://www.eclipse.org/uml2/5.0.0/UML',
'http://www.eclipse.org/papyrus/sysml/1.4/SysML',
'http://www.eclipse.org/papyrus/sysml/1.4/SysML/Blocks',
'http://www.eclipse.org/papyrus/sysml/1.4/SysML/Activities',
'http://www.eclipse.org/papyrus/sysml/1.4/SysML/Requirements',
'http://www.eclipse.org/papyrus/sysml/1.4/SysML/ModelElements')]
I have added the following code in the generate.java but still cannot work
Map<URI, URI> uriMap = resourceSet.getURIConverter().getURIMap();
// UML2 profiles
URI uri = URI.createURI("platform:/plugin/org.eclipse.uml2.uml.resources");
uriMap.put(URI.createURI(UMLResource.LIBRARIES_PATHMAP), uri.appendSegment("libraries").appendSegment(""));
uriMap.put(URI.createURI(UMLResource.METAMODELS_PATHMAP), uri.appendSegment("metamodels").appendSegment(""));
uriMap.put(URI.createURI(UMLResource.PROFILES_PATHMAP), uri.appendSegment("profiles").appendSegment(""));
// SysML profiles
uri = URI.createURI("platform:/plugin/org.eclipse.papyrus.sysml14");
uriMap.put(URI.createURI(SysMLResource.LIBRARIES_PATHMAP), uri.appendSegment("librairies").appendSegment(""));
uriMap.put(URI.createURI("pathmap://SysML14_PROFILES/"), uri.appendSegment("model").appendSegment(""));
The code like c.getAppliedStereotypes() returns null. I want to get the information of a requirement like the following code which returns nothing because of the getAppliedStereotype operation:
[for (re : uml::Class | uml::Class.allInstances()->select(cl : uml::Class | cl.getAppliedStereotype('SysML::Requirements::Requirement') <> null))]
--[re.name/]
Modellpfad : [re.qualifiedName/]
Id : [re.getValue(re.getAppliedStereotype('SysML::Requirements::Requirement'), 'id')/]
Text : [re.getValue(re.getAppliedStereotype('SysML::Requirements::Requirement'), 'text')/]
[/for]
Well, if none of your model elements have an applied stereotype, you will find no classes or objects. Thus, when you try to print the applied stereotype of all elements with an applied stereotype without first ensuring that the list is itself not null, you will fail.

Cucumber arity mismatch error

This step in my Ruby feature file to find and access a customer record:
When I search with the following details: "<recordReference>", "<secondIdentifier>", "<postcode>":
| recordReference | secondIdentifier| postcode |
| REFABCDE12345678| IDcode1234 | PC11 1PC |
It has this step definition:
When(/^I search with the following details: "(.*?)", "(.*?)", "(.*?)":$/) do |recordReference, secondIdentifier, postcode|
find(:css, "#dln").native.send_keys recordReference
find(:css, "#nino").native.send_keys secondIdentifier
find(:css, "#postcode").native.send_keys postcode
check 'confirmation'
click_button 'submit'
end
When it's run, I get the following error:
Cucumber::ArityMismatchError: Your block takes 3 arguments, but the Regexp matched 4 arguments.
features/step_definitions/refactored_commands.rb:207:in `/^I search with the following details: "(.*?)", "(.*?)", "(.*?)":$/'
What have I done wrong and how can it be fixed?
For info - I get the same error message if the parenthases are take out of the step definition:
When /^I search with the following details: "(.*?)", "(.*?)", "(.*?)":$/ do |recordReference, secondIdentifier, postcode|
The fourth argument is the DataTable. Remove the first 3 parameters and put in just the DataTable option, you will get all the data from the DataTable. Suggest you use dryRun=true option to let Cucumber create the proper step definition matcher, this is from my Java knowledge dont know how this dryRun option is in ruby.
Plus you will have to change your step in the feature file to remove the mentioned 3 parameters
It looks like you're mixing up scenario outlines with passing data tables to steps
From the format of your table it looks like what you're going for should actually be
Scenario Outline: xxx
...
When I search with the following details: "<recordReference>", "<secondIdentifier>", "<postcode>"
...
Examples:
| recordReference | secondIdentifier| postcode |
| REFABCDE12345678| IDcode1234 | PC11 1PC |
and then each the outline will be called once for each row of Examples with the values filled in - so your step would be
When(/^I search with the following details: "(.*?)", "(.*?)", "(.*?)"$/) do |recordReference, secondIdentifier, postcode|
...
end
On a side note - is there any reason you're calling .native.send_keys - I believe every driver now supports the normal Capybara send_keys API so it would just be find(:css, '#dln').send_keys recordReference (or of course just fill_in('dln', with: recordReference) )

cucumber ActiveRecord::ConnectionNotEstablished

The exception I am getting is "ActiveRecord::ConnectionNotEstablished: No connection pool for ActiveRecord::Base". I am really on the deep end of the pool (no pun intended) with this one. I really don't understand the connection and connection pool handling, even as much as I have studied this problem. I'm assuming this might be scope related inside of Cucumber, but I do not know. Any and all assistance is appreciated.
Here are the details:
The exception occurs when I perform a count from a Then clause:
WorkTable.where('? is not null',col['COLUMN_NAME']).count
It does not occur if I send the sql directly through the connection:
WorkTable.connection.select_all(st.encode('utf-8')).first['nulls']
My scenario reads as follows:
Scenario: CompanyMaster test for null value
Given table dbo.base_table in stage
Then these columns are expected to be not null
| COLUMN_NAME | nulls |
| id | 0 |
| company_name | 0 |
I establish my class in my env.rb:
class WorkTable < ActiveRecord::Base
end
ActiveRecord::Base.configurations = YAML.load_file(yaml) # yaml is database.yml file name
I establish my connection in a Given clause:
Given(/^table (\w+)\.?([\w_]+) in (\w+)(?: as (\w+))?$/) do |schema,name,env,id|
#sc_name = schema_file_name(schema,name)
WorkTable.logger.info title_line("* Active table(#{#sc_name}) *")
case id
# ActiveRecord::Base.configurations[env]
...
else
WorkTable.table_name = #sc_name
WorkTable.establish_connection(env.to_sym)
# ary = get_tables(WorkTable,schema:schema)
# expect( ary.any?{|s| s.casecmp(name)==0 } ).to eq(true)
end
end
I execute my test in a Then clause:
Then(/^these columns are expected to be not null$/) do |columns|
# expected is an instance of Cucumber::Ast::Table
WorkTable.logger.info title_line('Columns cannot be null')
results = []
columns.hashes.each {|col|
results << {
'COLUMN_NAME' => col['COLUMN_NAME'],
'nulls' => WorkTable.where('? is not null',col['COLUMN_NAME']).count.to_s
}
}
columns.diff!(results,surplus_row: false)
end
It is the WorkTable.where that throws the "ActiveRecord::ConnectionNotEstablished: No connection pool for ActiveRecord::Base". Again, if I use the WorkTable.connection method, I do not get it. Also, it executes fine if I copy all the function code to single ruby script.
I see the following when I "pp WorkTable.connection":
#<ActiveRecord::ConnectionAdapters::SQLServerAdapter version: 4.2.2, mode: dblib, azure: false>
And I see the following when I "pp WorkTable.connection_pool":
#<ActiveRecord::ConnectionAdapters::ConnectionPool:0x42f5238
#automatic_reconnect=true,
#available=
#<ActiveRecord::ConnectionAdapters::ConnectionPool::Queue:0x42f4f20
#cond=
#<MonitorMixin::ConditionVariable:0x42f4ed8
#cond=
#<ConditionVariable:0x42f4de8
#waiters=[],
#waiters_mutex=#<Mutex:0x42f4d58>>,
#monitor=
#<ActiveRecord::ConnectionAdapters::ConnectionPool:0x42f5238 ...>>,
#lock=#<ActiveRecord::ConnectionAdapters::ConnectionPool:0x42f5238 ...>,
#num_waiting=0,
#queue=[]>,
#checkout_timeout=5,
#connections=
[#<ActiveRecord::ConnectionAdapters::SQLServerAdapter version: 4.2.2, mode: dblib, azure: false>],
#mon_count=0,
#mon_mutex=#<Mutex:0x42f51c0>,
#mon_owner=nil,
#reaper=
#<ActiveRecord::ConnectionAdapters::ConnectionPool::Reaper:0x42f51a8
#frequency=nil,
#pool=#<ActiveRecord::ConnectionAdapters::ConnectionPool:0x42f5238 ...>>,
#reserved_connections=
#<ThreadSafe::Cache:0x42f4fc8
#backend=
{16931712=>
#<ActiveRecord::ConnectionAdapters::SQLServerAdapter version: 4.2.2, mode: dblib, azure: false>},
#default_proc=nil>,
#size=5,
#spec=
#<ActiveRecord::ConnectionAdapters::ConnectionSpecification:0x42f55c8
#adapter_method="sqlserver_connection",
#config=
{:host=>"server_name",
:database=>"mssb_stg",
:encoding=>"utf-8",
:adapter=>"sqlserver",
:timeout=>5000}>>
Ruby 1.9.3, activerecord (4.2.0), activerecord-sqlserver-adapter (4.2.2), and cucumber (1.3.18). And sql server 2014 [this has been a bugger for me].
Thank you for you time and consideration.
dvn
== Additional detail ==
Ignore the sql-server reference. I get the same exception when I reconfigure to work with SqLite. So it is not related to db platform.
Check your env.rb, conf in supports, it seems you are making connections in steps, ideally you should do it in before_scenario or before feature file rather than per steps.
It could be possible after steps your connection is not working properly.

Shibboleth authentication in Rails

I am having a struggle getting this to work so I've created a hell-world Rails app to try and get this to work.
Here's the repo with the code that is not working: https://github.com/pitosalas/shibtry
Here's what I've done starting from an empty Rails application:
I've added two gems to gem files:
gem 'omniauth-shibboleth'
gem 'rack-saml'
I got the shibboleth meta data from my university's web site and converted it using shib_conv.rb into the corresponding YAML: ./config.yml
I've updated routes adding get '/auth/:provider/callback', to: 'sessions#create'
I've put a breakpoint at SessionController#create
I've added initializers: omniauth.rb:
Rails.application.config.middleware.use OmniAuth::Builder do
provider :shibboleth, {
:shib_session_id_field => "Shib-Session-ID",
:shib_application_id_field => "Shib-Application-ID",
:debug => true,
:extra_fields => [
:"unscoped-affiliation",
:entitlement
]
}
end
I've added rack_sam.rb initializer:
Rails.application.config.middleware.insert_after Rack::ETag, Rack::Saml,
{ :metadata => "#{Rails.root}/config/metadata.yml"}
Now, run the server and go to http://0.0.0.0:3000/auth/shibboleth and I get an error:
undefined method `[]' for nil:NilClass'
which is traced back to this line in rack-saml/misc/onelogin_setting.rb line 13 which is:
settings.idp_sso_target_url = #metadata['saml2_http_redirect']
in other words, looking for the metadata hash for that key. It happens that in my metadata.yml file that key is present, but by the time I get to this onelogin_setting.rb line 13, #metadata is nil (it should contain the contents of the file) and consequently that key doesn't exist.
And that's where, for now, the trail dries up.
I bypassed Shibboleth totally. My goal was to allow login to my universities authentication system specifically to allow students to log in with their student login, which is fronted by google apps. So this was much easier: https://developers.google.com/identity/sign-in/web/
Looks like you forgot to add your config file to the initializer:
Rails.application.config.middleware.insert_after Rack::ETag, Rack::Saml,
{
:metadata => "#{Rails.root}/config/metadata.yml",
:config => "#{Rails.root}/config/rack-saml.yml"
}
And the saml_idp setting in the rack-saml.yml must match the key for the idp_lists entry in your metadata.yml

With Zabbix API, how do I get the values of items/resources rather than just the ID's?

I have some data in a Custom Screen in Zabbix, and would like to pull the data from the screen via the API. I'm using this Ruby gem: https://github.com/express42/zabbixapi
I'm able to successfully connect and query, but the results I'm getting are not very useful:
p zbx.query(
:method => "item.get",
:params => {
:itemids => "66666",
:output => "extend"
}
)
# [{"itemid"=>"66666", "type"=>"0", "snmp_community"=>"", "snmp_oid"=>"", "hostid"=>"77777", "name"=>"Fro Packages", "key_"=>"system.sw.packages[davekey1|davekey2|davekey3|davekey4]", "delay"=>"300", "history"=>"90", "trends"=>"365", "status"=>"0", "value_type"=>"1", "trapper_hosts"=>"", "units"=>"", "multiplier"=>"0", "delta"=>"0", "snmpv3_securityname"=>"", "snmpv3_securitylevel"=>"0", "snmpv3_authpassphrase"=>"", "snmpv3_privpassphrase"=>"", "formula"=>"1", "error"=>"", "lastlogsize"=>"0", "logtimefmt"=>"", "templateid"=>"88888", "valuemapid"=>"0", "delay_flex"=>"", "params"=>"", "ipmi_sensor"=>"", "data_type"=>"0", "authtype"=>"0", "username"=>"", "password"=>"", "publickey"=>"", "privatekey"=>"", "mtime"=>"0", "flags"=>"0", "filter"=>"", "interfaceid"=>"25", "port"=>"", "description"=>"", "inventory_link"=>"0", "lifetime"=>"30", "snmpv3_authprotocol"=>"0", "snmpv3_privprotocol"=>"0", "state"=>"0", "snmpv3_contextname"=>""}]
You can see that it's returning a bunch of ID's for the items, including the correct keys, but I can't seem to get the actual plain text values, which is the data I'm interested in.
I started with the screen_id, then got the screenitem_id, now the item_id, but I don't seem to be getting any closer to what I want!
Thanks for any help
Getting items or getting hosts means getting their description, not the data. is You are after history. Reading the actual Zabbix user manual and API docs is highly recommended.

Resources