jruby include java class performance vs include a package - module

I have a jruby rails app with a ruby module in lib that is name-spacing my java objects so I don't have conflicts.
I'm wondering what the difference is between including the specific classes in that module and including the package. I've included the sample code below.
In the console, for example 1 when I say MyMod:: and hit tab, it has (for example) 101 methods and class options with MyMod::MyClass being one of them.
For example 2, when I hit MyMod:: and tab, it only has 100 method/class options and it doesn't contain MyClass. If I then go and reference MyMod::MyClass, then run that MyMod:: tab again, I now have 101 options and MyClass is listed.
Here's my question. What's the difference between referencing these classes immediately in my module à la example 1 vs having them load on demand like example 2. If I have a package with about 20 classes that I use, is it preferred to have them loaded on demand or up front, and is there any overhead to loading this on demand, à la example 2
Sample Code:
example 1
module MyMod
MyClass = Java::my.package.MyClass
....
end
vs
example 2
module MyMod
include_package "my.package"
end

If you really are going to use a class, it is going to cost you something at some point. It doesn't matter whether loading it specifically or on-demand. I think for your 2 examples, if you do use MyClass, then there's no difference. On the other hand, if MyClass is never used, then example 1 is clearly wasting something.
Also, include_package does not really pull the whole package in, but kind of like establishing a search scope when needing a class. Generally it is not recommended to use include_package. See JRUBY-2376 for problems it has.

I got slightly different results. Perhaps you're using a different auto-completer?
irb(main):001:0> module MyMod;MyClass = Java::JavaUtil::Date;end
=> Java::JavaUtil::Date
irb(main):002:0> module OtherMod;include_package "Java.Util";end
=> nil
irb(main):003:0> MyMod.methods.size
=> 109
irb(main):004:0> OtherMod.methods.size
=> 109
irb(main):005:0> require 'irb/completion'
=> true
irb(main):006:0> MyMod::
Display all 110 possibilities? (y or n)
irb(main):006:0> OtherMod::
Display all 109 possibilities? (y or n)
irb(main):006:0> OtherMod::
irb(main):007:0*
As to your question, I don't know for sure. But if I had to guess, d'd say that as ruby is dynamic, neither approach loads anything up-front.

Related

Laravel factories slowing down testing due to nested relationships

For context, I'm working on a RNG-based motorsport simulator, for lack of a better term. Users can create universes (think FIA in real life terms), in a universe they can create series (think F1, F2, F3 etc) and in each series they can create seasons. In each of these, users can create additional models;
In a universe, a user can create teams and drivers.
In a season, a user can create a calendar using circuits they've added outside any universe, entrants (based on teams they've created in the parent universe) and to these entrants they can add drivers (based on drivers created), which I called "lineups".
The deeper I go with testing these relationships, the more models I need to create through factories to be able to test properly, and the longer it takes for a test to run. I've got a pretty simple test to verify a universe owner can add a driver to an entrant belonging to that universe;
test('a universe owner can add drivers to entrants', function () {
$user = User::factory()->create();
$season = createSeasonForUser($user);
$driver = Driver::factory()->for($season->universe)->create();
$entrant = Entrant::factory()->for($season)->create();
$this->actingAs($user)
->post(route('seasons.lineups.store', [$season]), [
'driver_id' => $driver->id,
'entrant_id' => $entrant->id,
'number' => 2,
])
->assertRedirect(route('seasons.lineups.index', [$season]));
$this->assertDatabaseCount('lineups', 1);
$this->assertCount(1, $entrant->drivers);
$this->assertCount(1, $season->drivers);
});
I've got two helper functions to quickly create a series and/or season belonging to a specific user;
function createSeriesForUser(User $user): Series
{
return Series::factory()->for(Universe::factory()->for($user)->create())->create();
}
function createSeasonForUser(User $user): Season
{
$series = createSeriesForUser($user);
return Season::factory()->for($series)->create();
}
As you can see, to test one part of the process, I need to create six models through factories (with some of these factories sometimes calling more factories). I ran the tests five times, timing each part of the test (factories, the actual request, and the assertions), and the factories take up 1,9 seconds on average, with the rest of the tests taking up 0,015 seconds, which doesn't seem right to me.
Ideally I'd create all required database entries before each test file is run, but I've understood this is bad practice. Is there another way to speed up the tests? Sadly I can't make the relationships less nested or complicated, since these are simply the requirement of the website I'm building.
Alternatively, is this approach in general even the right way to test my controller's functionality, or can it be done differently?
To not clutter up the question too much, here's a pastebin with all current factories
Turns out Faker's image() is really slow. I replaced the 'avatar' => $this->faker->image(), in my UserFactory with 'avatar' => null,, and my entire test suit now runs in barely over three seconds, or a second if I run them in parallel.

MAIN subroutine

Scenario
Imagine that you have a module X whose functionalities are available to the user through a Command Line Interface. Such module doesn't do much in and of itself but it allows for other people to create plugin-like modules they can hook-up to module X. Ideally, the plugins could be used through X's CLI.
Thus my question:
What do you need to do in order to hook-up whatever functionality
a plugin might provide to X's CLI?
This means the plugin would need to provide some structure describing the command, what needs to be called and hopefully a usage message for the plugin. Therefore, when you run X's CLI, the plugin's command and help message shows up in the regular X's CLI's help message.
Example
main.p6:
use Hello;
use Print;
multi MAIN('goodbye') {
put 'goodbye'
}
lib/Hello.pm6:
unit module Hello;
our %command = %(
command => 'hello',
routine => sub { return "Hello" },
help => 'print hello.'
);
lib/Print.pm6:
unit module Print;
our %command = %(
command => 'print',
routine => sub { .print for 1..10 },
help => 'print numbers 1 through 10.'
);
The program main.p6 is a simplified version of this scenario. I'd like to integrate the information provided by both Hello.pm6 and Print.pm6 through
their respective %command variables into two new MAIN subs in main.p6.
Is this possible? If so, how would I go about achieving it?
This looks kinda specific for a StackOverflow question, but I will give it a try anyway. There are a couple of issues here. First one is to register the commands as such, so that MAIN can issue a message saying "this does that", and second is to actually perform the command. If both can be known at compile time, this can probably be fixed. But let's see how the actual code would go. I'll just do the first part, and I leave the rest as an exercise.
The first thing is that %command needs somehow to be exported. You can't do it the way you are doing it now. First, because it's not explicitly exported; if it were, you would end up with several symbols with the same name in the outer scope. So we need to change that to a class, so that the actual symbols are lexical to the class, and don't pollute the outer scope.
unit class Hello;
has %.command = %(
command => 'hello',
routine => sub { return "Hello" },
help => 'print hello.'
);
(Same would go for Print)
As long as we have that, the rest is not so difficult, only we have to use introspection to know what's actually there, as a small hack:
use Hello;
use Print;
my #packages= MY::.keys.grep( /^^<upper> <lower>/ );
my #commands = do for #packages -> $p {
my $foo = ::($p).new();
$foo.command()<command>
};
multi MAIN( $command where * eq any(#commands) ) {
say "We're doing $command";
}
We check the symbol table looking for packages that start with a capital letter, followed by other non-capital letter. It so happens that the only packages are the ones we're interested in, but of course, if you would want to use this as a plugin mechanism you should just use whatever pattern would be unique to them.
We then create instances of these new packages, and call the command auto-generated method to get the name of the command. And that's precisely what we use to check if we're doing the correct command in the MAIN subroutine, by using the where signature to check if the string we're using is actually in the list of known commands.
Since the functions and the rest of the things are available also from #packages, actually calling them (or giving an additional message or whatever) is left as an exercise.
Update: you might want to check out this other StackOveflow answer as an alternative mechanism for signatures in modules.

ContentHandler issues (circular reference) in Orchard

crosspost: https://orchard.codeplex.com/discussions/459007
First question I have is what would be the repercussions of having 2 PartHandlers for the same Part in 2 different modules?
I got into this predicament because I have to run a method once a specific Content Type is created. It would be as easy to hook onto OnCreated for the part, however, here is my scenario:
Module A contains the part and the original handler
Module B contains the service where the method is
Module B has a reference to Module A
Therefore, I am unable to reference Module B within Module A (circular reference). So what I did was to copy the exact same PartHandler in Module A and placed it in Module B.
Would anything be wrong with that?
Then comes my second question, which I think could solve all these problems: Can we create a PartHandler for the Content Item's default Content Part? (i.e. the part where all custom fields are attached to)
This would definately make things easier as I could consolidate stuff that need to run there.
UPDATE 1 (to better explain question 2)
ContentDefinitionManager.AlterPartDefinition("EventItem",
builder => builder
.WithField("StartDate", cfg => cfg
.OfType("DateTimeField")
.WithDisplayName("Start Date")
.WithSetting("DateTimeFieldSettings.Display", "DateOnly")
.WithSetting("DateTimeFieldSettings.Required", "true"))
.WithField("StartTime", cfg => cfg
.OfType("DateTimeField")
.WithDisplayName("Start Time")
.WithSetting("DateTimeFieldSettings.Display", "TimeOnly"))
.WithField("EndDate", cfg => cfg
.OfType("DateTimeField")
.WithDisplayName("End Date")
.WithSetting("DateTimeFieldSettings.Display", "DateOnly"))
.WithField("EndTime", cfg => cfg
.OfType("DateTimeField")
.WithDisplayName("End Time")
.WithSetting("DateTimeFieldSettings.Display", "TimeOnly"))
.WithField("Intro", cfg => cfg
.OfType("TextField")
.WithDisplayName("Intro")
.WithSetting("TextFieldSettings.Flavor", "textarea"))
ContentDefinitionManager.AlterTypeDefinition(
"EventItem"
, cfg =>
cfg
.DisplayedAs("Event Item")
.WithPart("TitlePart")
.WithPart("EventItem")
.WithPart("LocationPart")
.WithPart("AutoroutePart", builder => builder
.WithSetting("AutorouteSettings.AllowCustomPattern", "true")
.WithSetting("AutorouteSettings.AutomaticAdjustmentOnEdit", "false")
.WithSetting("AutorouteSettings.PatternDefinitions", "[{Name:'Title', Pattern: 'learn/events/{Content.Slug}', Description: 'learn/events/event-title'}]")
.WithSetting("AutorouteSettings.DefaultPatternIndex", "0"))
.WithPart("CommonPart")
.Draftable()
.Creatable()
);
I'm talking about creating a ContentHandler for the EventItem part which holds all the custom fields. How can I go about it when EventItemPart is not defined in any class in the solution?
The following below won't work since it can't find the class EventItemPart:
OnCreated<EventItemPart>((context, keynotes) =>
questionService.SetDefaultQuestions(context.ContentItem));
Cross-answer as well.
Bertrand's perfectly right. Why do you need to reference B in A in first place? If the service from B needs A and A needs this service, then it belongs to A (at least the interface - contract).
You can always split interface and actual implementation for your service, having one in different module than another. If implementation of your service requires stuff from B, then put the interface in A, but actual implementation in B. This way A doesn't even need to know about the existence of B, but still be able to use the service via it's interface - it's the beauty of IoC pattern and Orchard modularity:)
You may use ContentPart or IContent as a type argument in handler generic methods. It's perfectly valid. This way you'd be able to plug in to events on all items, and perform custom filtering afterwards (based on type name, some field existence etc.). In your case it may look like:
OnCreated<ContentPart>((context, part) =>
{
if(part.ContentItem.ContentType != "EventItem") return;
questionService.SetDefaultQuestions(context.ContentItem);
});
Update: no need to do this: .WithPart("EventItem"). This 'fake' part will be automatically added by framework.
Cross-answer:
none
However, repeating yourself is almost always wrong, especially if it's done for a bad reason. Why is are the service and the part in two different modules? Why does A need B? A circular reference indicates tight coupling. If the tight coupling is justified, then it should happen in a single module. If it's not, then you need to re-do your design to remove it.
You can create a handler for anything, but your explanation of your scenario is way to vague and abstract to give any useful advice.

Abstraction over container iterators

I'm talking about Ada 2012 here.
I'll let the code speak first:
with Ada.Containers.Hashed_Maps;
with Ada.Strings.Unbounded;
with Ada.Strings.Unbounded.Hash_Case_Insensitive;
with Ada.Strings.Unbounded.Equal_Case_Insensitive;
package Environments is
type Environment is tagged private;
function Variable (
E : in Environment;
Name : in Ada.Strings.Unbounded.Unbounded_String
)
return Ada.Strings.Unbounded.Unbounded_String
with Inline;
procedure Set_Variable (
E : in out Environment;
Name : in Ada.Strings.Unbounded.Unbounded_String;
Value : in Ada.Strings.Unbounded.Unbounded_String
)
with Inline;
private
package Variable_Maps is new Ada.Containers.Hashed_Maps (
Key_Type => Ada.Strings.Unbounded.Unbounded_String,
Element_Type => Ada.Strings.Unbounded.Unbounded_String,
Hash => Ada.Strings.Unbounded.Hash_Case_Insensitive,
Equivalent_Keys => Ada.Strings.Unbounded.Equal_Case_Insensitive,
"=" => Ada.Strings.Unbounded."="
);
type Environment is tagged record
Variables : Variable_Maps.Map;
end record;
end Environments;
What we have here is an example package fairly well illustrating my problem. I'm storing some environment variables in Hashed_Map, but I want to build a abstraction layer over the standard container, so I can in future change the underlaying container without changing any code in my package's customers.
Getting and setting variables is easy - as declared above. The real problem is iterating. I'd like to let my package's customers to iterate over the environment and get both key and value for each element easily.
As I'm using Ada 2012 the best way would be to use iterators, but how? I could return a cursor to the underlaying container, but again, this cursor's interface would be container-dependent.
What's the best way to achieve such abstraction over standard container iteration?
Take a look at Ada Gems #127 and #128, "Iterators in Ada 2012, Parts 1 & 2" for guidance on how to create your own iterators.

Ninject - How to dynamically select an implementation to bind to an interface

I'm currently using Ninject to create instances of interfaces in a WCF Services application.
Bind<IObjA>().To<ObjA>().InRequestScope();
Bind<IObjB>().To<ObjB>().InRequestScope();
Bind<IObjC>().To<ObjC>().InRequestScope();
It works great, but we are going to have several implementations of IObjC. What options do I have for continuing fluid assignment of implementation to interface for IObjA/IObjB but allowing for configurable assignment for IObjC?
I found a related question on SO but I don't know if I can support both a fluid and a configurable approach simultaneously.
For example, can I use Ninject.extensions.xml for IObjC while continuing to use the above approach for IObjA and IObjB?
Is it advisable to have conditional assignment for IObjC? That seems dirty but at the same time appears very simple.
if (condition1)
Bind<IObjC>().To<ObjC1>().InRequestScope();
else if (condition 2)
Bind<IObjC>().To<ObjC2>().InRequestScope();
Also, I know other frameworks like Castle support XML configuration but I would like to continue using Ninject.
1 - your bindings to IObjC have nothing to do with any other bindings. it doesn't matter where, when, or how you bind other services.
2 - you can use the XML extensions, but I would ask why you think you need it to be configurable.
3 - there are 2 possibilities for your conditional. first is that you want to make a decision at startup to determine whether to use ObjC1 for the entire lifetime of the app, or ObjC2. if that's the case, your code is ok. however, if you want to dynamically decided which object to use each time you resolve the binding, you will need to put the condition inside your binding, like so:
Bind<IObjC>().ToMethod( ctx => condition ? ctx.Kernel.Get<ObjC1>() : ctx.Kernel.Get<ObjC2>() );
alternately, you can use Named bindings:
Bind<ILog>().ToConstant( LogManager.GetLogger( "Accounting" ) ).Named( "Accounting" );
or "When" conditions to help:
Bind<ILog>().ToConstant( LogManager.GetLogger( "Background" ) ).When( context => context.Target != null && context.Target.Name == "backgroundLogger" );