How to initialize global variables in TurboGears 2 with values from a table - genshi

I need a global variable that I can call from the templates.
I edited app_globals.py in lib directory to declare PATH_TO_IMAGES like this
class Globals(object):
"""Container for objects available throughout the life of the application.
One instance of Globals is created during application initialization and
is available during requests via the 'app_globals' variable.
"""
PATH_TO_IMAGES = ""
def __init__(self):
"""Do nothing, by default."""
pass
Now I can call from any template the image path like this
<img src="${g.PATH_TO_IMAGES}/${p.image}" />
The image path is stored inside a settings table on the app's database, but I can't initialize it from Globals declaration, i get this error:
sqlalchemy.exc.UnboundExecutionError:
Could not locate a bind configured on
mapper
Mapper|Settings|settings,
SQL expression or this Session
My guess is that database binding happens after Globals is initialized. So my questions is, which is the best place to initialize a global variable in TurboGears 2 and which is the best practice to that.

Just use a cached property:
class Globals(object):
"""Container for objects available throughout the life of the application.
One instance of Globals is created during application initialization and
is available during requests via the 'app_globals' variable.
"""
#property
def PATH_TO_IMAGES(self):
try:
return self._path_to_images
except AttributeError:
self._path_to_images = db_session.query(XXX) # Fill in your query here
return self._path_to_images
PS : your question is a generic Python question really. I suggest you read the official Python docs before posting other similar questions.

You probably need to create your own database connection to get this data from the database.
In SQLAlchemy terms, you'll want to create your own engine, session, etc. Just make sure to clean up after you're done.
I would probably do this in app_cfg.py using on_startup to get it into the config, and then stick it in the Globals object later on if you still need to.

You may set PATH_TO_IMAGES to it's definite value once the models are initialized. The sooner being at the end of the 'init_model' function declared in model/init.py.

Related

How to create test data using Drivine and NestJS?

In the implementation of repositories, you inject the PersistenceManager interface using #InjectPersistenceManager(). For testing, the docs mention to use RunWithDrivine, and to import Drivine (through the AppModule) into the createTestingModule call. This allows the PersistenceManager to be injected in the repository to be used.
I create a temporary Docker container with a new Neo4j database for the tests to use (using a package called testcontainers). This database needs some data to be used. In the test setup, it is possible to get the PersistenceManager by retrieving it from the testing module using a string which normally the decorator provides: app.get("PersistenceManager:default") as PersistenceManager and while this works, it does not seem like the correct way to do it.
How would I get the PersistenceManager to set up the data (and do other things) properly?
app.get("PersistenceManager:default") as PersistenceManager
This is actually probably what you're looking to do, but need to add { strict: false } as a second parameter to the get method. Seeing as #InjectPersistenceManager() is just #Inject('PersistenceManager:database') and database is default by default, you have the correct token, so you probably just need to tell Nest to dig deeper than the top module, hence the{ strict: false } option

Make an independent copy of a model instance

I would like one instance of a model in memory to serve as a template for creating other objects for performance reasons, so that duplicates look like the original object but otherwise share no common components with the object they are initialized from, as if they were loaded with Model.find(template_object.id). I've tried some of the available solutions but none seems to do what I need: .dup and .deep_dup will create a new object with nil id and .clone will make some of the fields common to both the initializer and the initialized.
Currently my API is giving out the original objects that I keep as class variables, but I discovered that it leads to obscure memory leaks when the code using the objects manipulates their associations - these are kept in memory indefinitely. I hope that by giving out copies the associations of the template objects will stay untouched and the leak will be gone.
This sounds like the use case for defining a class and just initializing instances. You can customize whatever properties you want shared in the MyClass#new method. Without knowing more about your needs I will add that if you must store a template in memory you could store it as a class variable perhaps MyClass##template but would need to hear more to opine further. 😄
What I found when browsing rails source is the .instantiate method:
MyModel.instantiate(#my_other_instance.attributes_before_type_cast.deep_dup)

Ruby - Why is it possible to use Instance variables like everywhere

I'm into Ruby on Rails programming for almost 5 weeks now.
I was wondering why people always use instance variables instead of local ones.
I always thought that you would use instance variables only for classes (so these instance variables are the attributes of the class).
But people also use them not only for being attributes of a class. And this is the part where I am getting confused.
For instance, take a look at these lines of codes:
class Foo
def print_a_hello
puts "Hello World"
end
end
#instance_variable = Foo.new
#instance_variable.print_a_hello
# => "Hello World"
locale_variable = Foo.new
locale_variable.print_a_hello
# => "Hello World"
So, who of you got a great explanation for me?
I was wondering why people always use instance variables instead of locale ones.
I'm not sure how you get that impression. I certainly don't "always" use instance variables. I use instance variables when I need an instance variable, and I use local variables, when I need a local variable, and most code I see does it the same way.
Usually, it doesn't even make sense to interchange them. They have completely different purpose: local variables have static lexical scope, instance variables have dynamic object scope. There's pretty much no way to interchange them, except for the very narrow case of a simple single-file procedural script, where the dynamic scope of the top-level main object and the lexical scope of the script body are identical.
I always thought that you would use instance variables only for classes (so these instance variables are the attributes of the class).
No. Instance variables are attributes of the instance (i.e. object), not the class, that's why they are called "instance variables", after all. Class variables are attributes of the class, but class variables are a different beast and only used in very specific circumstances. (Classes are objects (i.e. instances), too, so they can have instance variables as well; there's generally no need to use class variables, which have some weird and un-intuitive properties, unless you specifically need those weird and un-intuitive properties).
For instance, take a look on this short codelines:
class Foo
def print_a_hello
puts "Hello World"
end
end
#instance_variable = Foo.new
#instance_variable.print_a_hello
# => "Hello World"
locale_variable = Foo.new
locale_variable.print_a_hello
# => "Hello World"
This is the case I mentioned above: in this specific case (and only in this case), the dynamic scope of the top-level main object and the static lexical scope of the script body are identical, so it doesn't matter whether you use a local variable of the script body or an instance variable of the main object.
However, if we make just a tiny change to that, by adding a second script and requireing it from the first, that condition will no longer hold, because we now have two separate script bodies and thus two separate script scopes, but still only one top-level object.
The idiomatic way in your example would definitely be to use a local variable, and nobody I know would do otherwise.
Best use case for instance variables is in Controller's when you want to pass parameter to the view.
Then you use something like
class TestController < ActionController::Base
def show
#usable_in_view = Test.first
not_usable_in_view = Test.first
end
end
In your view you can now use #usable_in_view, but cant use variable not_usable_in_view. Most people always use instance variable in controllers even if they do not need them in view, because they do not understand why they need instance variable
Instance variables are used so that they can be accessed in the view page.
Local variables are not accessible in the view. It has become the habit even I sometimes write instance variables though it is not required in the view.:-)
People probably get in the [bad] habit of using instance variables everywhere since it's common in Rails to use them to get information from the controller to the view.
In my own Ruby code I use instance variables only when I need to, local variables otherwise. That's the proper way to use Ruby.

Global variable that is accessible in models without passing any information from controller

I know how we can declare global variable in config file and then access through
Service Locator
Currently I am getting this Global variable in controller with the help of service locator and then pass it to models while creating object.
Question: Is it possible that I can get the Global variable in model directly rather than passing in all the models through controller?
Yes it is possible to get the variable declared in global file into model directly. Instead of declaring it as variable, just define it as constant in the global file so that you can access that variable easily in any models.
define('VAR_NAME',Value);
and access the variable using.
constant('VAR_NAME');
Hope it helps
Thanks

Using Dart as a DSL

I am trying to use Dart to tersely define entities in an application, following the idiom of code = configuration. Since I will be defining many entities, I'd like to keep the code as trim and concise and readable as possible.
In an effort to keep boilerplate as close to 0 lines as possible, I recently wrote some code like this:
// man.dart
part of entity_component_framework;
var _man = entity('man', (entityBuilder) {
entityBuilder.add([TopHat, CrookedTeeth]);
})
// test.dart
part of entity_component_framework;
var man = EntityBuilder.entities['man']; // null, since _man wasn't ever accessed.
The entity method associates the entityBuilder passed into the function with a name ('man' in this case). var _man exists because only variable assignments can be top-level in Dart. This seems to be the most concise way possible to use Dart as a DSL.
One thing I wasn't counting on, though, is lazy initialization. If I never access _man -- and I had no intention to, since the entity function neatly stored all the relevant information I required in another data structure -- then the entity function is never run. This is a feature, not a bug.
So, what's the cleanest way of using Dart as a DSL given the lazy initialization restriction?
So, as you point out, it's a feature that Dart doesn't run any code until it's told to. So if you want something to happen, you need to do it in code that runs. Some possibilities
Put your calls to entity() inside the main() function. I assume you don't want to do that, and probably that you want people to be able to add more of these in additional files without modifying the originals.
If you're willing to incur the overhead of mirrors, which is probably not that much if they're confined to this library, use them to find all the top-level variables in that library and access them. Or define them as functions or getters. But I assume that you like the property that variables are automatically one-shot. You'd want to use a MirrorsUsed annotation.
A variation on that would be to use annotations to mark the things you want to be initialized. Though this is similar in that you'd have to iterate over the annotated things, which I think would also require mirrors.

Resources