Using enum value for query result - graphene-python

I am trying to use an Enum in my project with custom strings, something like this:
class Fruit(Enum):
APPLE: "apple"
PEAR: "pear"
BANANA: "banana"
In my query object, I'm trying to use it as follows:
FruitEnum = graphene.Enum.from_enum(Fruit)
class Person(DjangoObjectType):
will_eat_fruit = graphene.List(lambda: FruitEnum)
For a person who will only eat apples, I'd expect to get the result ["apple"] but am instead getting ["APPLE"] and I'm having trouble figuring out how to get graphene to return the enum value while still using enums rather than strings.
Am I missing something?
(Using graphene 2.1.8).

Related

Access value from a Netsuite hash, Enumerator

Hi I am trying to extract a value from a Netsuite hash inside custom fields, and some others, which typically look like this - `
"custbody_delivery_ticket_number"=>
{
"script_id"=>"custbody_delivery_ticket_number",
"internal_id"=>"2701",
"type"=>"platformCore:DateCustomFieldRef",
"attributes"=> {
"value"=>"123abc"
}
}` and want the value of it inside of attributes.
Have tried many different ways, but one in particular -
delivery_ticket_number: "#{netsuite_sales_orders.custom_field_list.custom_fields.select['custbody_nef_meter_ticket_number']['attributes']['value']}",
throws error for class Enumerator, NoMethodError: undefined method `[]' for #Enumerator:0x00005589ec778730 which indicates may be getting close, but doing something wrong.
If anyone has any idea how to get values from these kind of hashes?
(Am told by the system admin that it is the correct custbody identifier)
Many Thanks
Eventually fixed this, grabbing Netsuite custom fields with a select of script_id by name,and map as below:
delivery_date:netsuite_sales_order.custom_fields_list.custom_fields.select { |field| field.script_id == 'custbody_delivery_date' }.map { |field| field.value }.first
First selecting the script_id by unique name, then mapping to the value. Was able to get any custom field like this, preferable as they can move and might not have the same index if use an index to grab them, fetching an incorrect value. This way ensures getting the correct data even if the item is moved up or down in the custom fields list.
Thanks for everyones help!

Trouble reading and binding yml data in ruby

I have a yaml file that includes the following:
:common
:substitue
:foo: fee
I read this data like:
data = YAML.load(erb_data[File.basename(__FILE__, '.*')].result(binding))
common = data[:common]
def substitute_if_needed(original_value)
mapping = common.dig(:substitue, original_value)
if mapping.nil? ? original_value : mapping
end
Unfortunately, this doesn't do the substitution that I want. I want to call substitute_if_needed('foo') and get 'fee' back. I also want to call substitute_if_needed('bar') and get 'bar' back.
How can I do this?
There are several problems in your code:
YAML example looks broken. The proper one should looks like:
common:
substitute:
foo: fee
You're trying to fetch common key in common = data[:common] using a symbol as a key, but it should be a string (data["common"]). Also, I'd say it's a bad idea to spilt fetching logic into two pieces - first extract "common" outside of substitute_when_needed and then dig into it inside.
if statement is broken. It should be either proper if or proper ternary operator.
Fixing all this gives us something like (I've just replaced a file with StringIO for convenience - to make the snippet executable as is):
yaml = StringIO.new(<<~DATA)
common:
substitute:
foo: fee
DATA
def substitute_if_needed(data, original_value)
mapping = data.dig("common", "substitute", original_value)
mapping.nil? ? original_value : mapping
end
data = YAML.load(yaml)
substitute_if_needed(data, "foo") # => "fee"
substitute_if_needed(data, "bar") # => "bar"

How to use polymorphism to remove a switch statement which compares strings?

I am new to Ruby, so let me describe the context of my problem first:
I have a json as input which has the following key / value pair:
{
"service": "update"
}
The value has many different values for example: insert,delete etc.
Next there is a method x which handles the different requests:
def x(input)
case input[:service]
services = GenericService.new
when "update"
result = services.service(UpdateService.new,input)
when "insert"
result = services.service(InsertService.new,input)
when "delete"
result = services.service(DeleteService.new,input)
....
....
else
raise "Unknown service"
end
puts JSON.pretty_generate(result)
end
What is bothering me is that I still need to use a switch statement to check the String values (reminds me of 'instance of' ugh..). Is there a cleaner way (not need to use a switch)?
Finally I tried to search for an answer to my question and did not succeed, if however I missed it feel free to comment the related question.
Update: I was thinking to maybe cast the string to the related class name as follows: How do I create a class instance from a string name in ruby? and then call result = services.services(x.constantize.new,input) , then the class names ofcourse needs to match the input of the json.
You can try something like:
def x(input)
service_class_name = "#{input[:service].capitalize}Service"
service_class = Kernel.const_get(service_class_name)
service_class.new(input).process
end
In addition you might want to check if this is a valid Service class name at all.
I don't understand why you want to pass the service to GenericService this seems strange. let the service do it's job.
If you're trying to instatiate a class by it's name you're actually speaking about Reflection rather than Polymorphism.
In Ruby you can achieve this in this way:
byName = Object.const_get('YourClassName')
or if you are in a Rails app
byName= 'YourClassName'.constantize
Hope this helps
Just first thoughts, but you can do:
eval(services.service("#{input[:service].capitalize}Service.new, #{input})") if valid_service? input[:service]
def valid_service?
w%(delete update insert).include? input[:service]
end
As folks will no doubt shout, eval needs to be used with alot of care

A ruby SPARQL query that SELECT(s) all triples for a given subject

I'm using the following ruby library to query a SPARQL endpont.
http://ruby-rdf.github.io/sparql-client/
I'm really close to achieving what I want. With the following code I can get a print out of all the triples in my database.
sparql = SPARQL::Client.new("http://localhost:3030/ds/query")
query = sparql.select.where([:s, :p, :o]).offset(100).limit(1000)
query.each_solution do |solution|
puts solution.inspect
end
But now I want to change this just slightly and select all the triples for a given subject. I thought the following would work, but it doesn't.
sparql = SPARQL::Client.new("http://localhost:3030/ds/query")
itemname = "lectio1"
query = sparql.select.where(["<http://scta.info/items/#{itemname}>", :p, :o]).offset(100).limit(1000)
query.each_solution do |solution|
puts solution.inspect
end
This would work in a straightforward SPARQL syntax, but somehow replacing the symbol :s with the literal subject I want queried doesn't work. The error that Sinatra gives me is:
expected subject to be nil or a term, was "<http://scta.info/items/lectio1>";
As you noted in the comments,
The error that Sinatra gives me is: expected subject to be
nil or a term, was "<http://scta.info/items/lectio1>"
You're pasing the method a string, but it's expecting nil or a term. The kind of term that it's expecting is an RDF::Term. In your particular cases, you want a URI (which is a subclass of RDF::Resource, which is a subclass of RDF::Term). You can create the reference that you're looking for with
RDF::URI.new("http://scta.info/items/#{itemname}")
so you should be able to update your code to the following (and depending on your imports, you might be able to drop the RDF:: prefix):
sparql = SPARQL::Client.new("http://localhost:3030/ds/query")
itemname = "lectio1"
query = sparql.select.where([ RDF::URI.new("http://scta.info/items/#{itemname}"), :p, :o]).offset(100).limit(1000)
query.each_solution do |solution|
puts solution.inspect
end

Ruby: How to get a class based on class name and how can I get object's field based on field name?

Question 1
How to get a class given a class name as a string ?
For example, say Product class has do_something method:
str = "product"
<what should be here based on str?>.do_something
Question 2
How to get object's field given a field name as a string ?
For example, say Product class has price field:
str = "price"
product = Product.new
product.<what should be here based on str?> = 1200
Jacob's answer to the first question assumes that you're using Rails and will work fine if you are. In case you're not you can call Kernel::const_get(str) to find an existing constant by name.
send is a pure ruby. There's no need to intern your strings with send though (convert them to symbols), straight strings work fine.
Use capitalize and constantize:
str.capitalize.constantize.do_something
Use send:
product.send(str + '=', 1200)

Resources