scopes with lambda and arguments in Rails 4 style? - ruby-on-rails-4

I'm wondering how the following is done in Rails 4 or if I just use the Rails 3 approach for using a lambda that can pass an argument the same way with 4 as I do with 3.
I'm pretty new to Rails 3 and trying to work through some samples running Rails 4.
Here is my Rails 3 code:
class Person < ActiveRecord::Base
scope :find_lazy, lambda {|id| where(:id => id)}
end
# In console I can call
Person.find_lazy(1)
So if this is the Rails 4 way is to use the -> {}, that's a lambda, right? scope :all_lazy, -> { select("*") } What if I needed an argument. I tried a few different ideas and get argument errors in the console when using the -> {}.

I think it should be:
scope :find_lazy, -> (id) { where(id: id) }

Ruby has not deprecated the old style of lambda either, so if you feel more comfortable using that by all means go for it.
I don't personally like the stabby lambda's syntax myself but eventually they will probably become the norm so it doesn't hurt to get used to them.

Rails 4, you can do:
scope :find_lazy, -> (id) { where(id: id) }
That was in the old ruby:
:id => id
Better hash:
id: id

guy I was usually using the below programming syntax
scope :find_lazy, -> (id) { where(id: id) }
But when I was reviewing my code using Codacy I found it alerting me about this syntax
Use the `lambda` method for multiline lambdas.
I changed it to be and it working well
scope :find_lazy, lambda {|id|
where(id: id)
}

To support associations:
scope :find_lazy, -> (object) { where(object_id: object.id) }

scope :find_lazy, -> (id) { where(id: id) }
is equivalent with
self.find_lazy(id)
where(id: id)
end
Based on ruby on rails guide: Using a class method is the preferred way to accept arguments for scopes.
There is no reason to use scopes together with lambdas in preference to class methods. It is a matter of personal preference. But, if you want to follow the guidelines, you should use the class method when arguments are involved.

Related

Authorization based on multiple scopes in C# web API ( scopes based authorization ) using policies

I am posting this to share information to Authorization in C# WEB API using multiple scopes.
After posting this user-defined I got a simple answer from https://stackoverflow.com/users/4830196/ryan-wilson
Thank you Ryan-Wilson for commenting your answer instead of just ignoring question.
i.e
options.AddPolicy("ReadPolicy", policy => {
policy.RequireClaim("scope","scope1","scope2");
});
Authorizing based on a single scope I found reference from https://docs.duendesoftware.com/identityserver/v5/apis/aspnetcore/authorization/
i.e in :
services.AddAuthorization(options =>
{
options.AddPolicy("read_access", policy =>
policy.RequirementClaim("scope", "item1.read");
});
and utilizing it at the end point:
public class DataController : ControllerBase
{
[Authorize(Policy="read_access")]
public async Task<IActionResult> Get()
{
return logic here
}
}
The above only works for single scope i.e item1.read. If we want a logic to make the end point accessible with either of multiple scopes if have written following logic.
options.AddPolicy("ReadPolicy", policy => {
policy.RequireAssertion(context => {
return context.User.HasClaim(c =>
(c.Type == "scope" &&
(c.Value.Contains("item.read") ||
c.Value.Contains("complete.read")
)
));
});
});
Here the scope item1.read means providing scope for only 1st item and scope complete.read means full access.
Hope this might helpful for any of us. Please hit like if this is understandable and useful. If not please share comment on how to improve my skills.
Thank you,
Naveen Devi.

Adonsjs 4 - what is use() and why it not work in version 5

I try to understand the code https://github.com/nuxt-community/adonuxt-template .
What is use() and why it not work in version 5.
How to change?
const { Ignitor } = require('#adonisjs/ignitor')
new Ignitor(require('#adonisjs/fold'))
.appRoot(__dirname)
.fireHttpServer()
.then(() => {
return use('App/Services/Nuxt').build()
})
.then(() => {
use('Logger').info('Nuxt is ready to handle requests')
})
.catch(console.error)
And how to rewrite that files to work in version 5:
https://github.com/nuxt-community/adonuxt-template/blob/master/start/app.js
https://github.com/nuxt-community/adonuxt-template/blob/master/app/Commands/NuxtBuild.js
https://github.com/nuxt-community/adonuxt-template/blob/master/app/Controllers/Http/NuxtController.js
https://github.com/nuxt-community/adonuxt-template/blob/master/app/Services/Nuxt.js
The use() method which was used to import dependencies from ioc container aka adonis-fold has been removed in v5. The alternative to that method is now ESM imports which uses #ioc prefix. Kindly follow this introductory guide https://docs.adonisjs.com/releases/introducing-adonisjs-v5-preview#esm-imports-all-the-way.
AdonisJS v5 has various breaking changes with regards to v4, also there are major changes in dev tools as well such as typescript as the first-class citizen, adonis cli is deprecated. Also AdonisJS team is expected to release upgrade guide in near future.
use () is provided by the IoC container AdonisJs (adonis-fold).
This function will try to resolve the binding or namespace defined in the Adonis config file and then fall back to the default require() function to import the package if it doesn't find anything.

What is the equivalent to autofacs "WithParameter" in DryIoc?

In an effort to migrate from Autofac to DryIoc, I've run into a scenario whereby I need to pass a parameter value into the constructor of a service.
// given the following class
public class SomeService
{
public SomeService(Foo foo, Bar bar) { }
}
// in autofac it looks like this
container.RegisterType<SomeService>()
.WithParameter("foo", SomeFoo.Value)
.WithParameter("bar", SomeBar.Value)
.AsSelf();
What would the equivalent be in DryIoc?
Right now I'm attempting to use RegisterDelegate, but I'm not sure if I'm on the right path.
container.RegisterDelegate(x => new SomeService(SomeFoo.Value, SomeBar.Value));
container.Register<SomeService>(
made: Made.Of(Parameters.Of
.Name("foo", _ => SomeFoo.Value)
.Name("bar", _ => SomeBar.Value)));
Here are possible overloads: https://www.fuget.org/packages/DryIoc.dll/4.2.0/lib/netstandard2.0/DryIoc.dll/DryIoc/Parameters
There is a similar to Parameters PropertiesAndFields class to specify the property injection details.
In addition there is a DryIoc.Syntax.Autofac package you might be interested in https://www.fuget.org/packages/DryIoc.Syntax.Autofac.dll
As of V1 it covers only a small subset of Autofac API surface, but I encourage you to look into its source code and maybe help with PR ot two :)
https://github.com/dadhi/DryIoc/tree/master/src/DryIoc.Syntax.Autofac

Emberjs: Access controller dependency on a different namespace

In my ember application I want to have modules on different namespaces. I have an App Namespace and for each module there is an App.ModuleName namespace.
So far so good, I can access everything so far using App/ModuleName/SomeResource syntax. Now I have a controller that has a dependency on a controller in one of the module namespaces. I put up the controllers like this:
App.ModuleName.FooController = Ember.Controller.extend({
fooVal: 42
});
App.SomeController = Ember.Controller.extend({
needs: ['App/ModuleName/Foo', 'bar']
});
That seem to work so far telling by ember not complaining that the needed controller doesn't exist.
Now, how do I acces the controller in my handlebars template? For the bar controller its easy, just using controllers.bar.someProperty but I cannot access the App.ModuleName.FooController. I tried:
{{controllers.App/ModuleName/Foo.fooVal}}
{{controllers.App.ModuleName.Foo.fooVal}}
{{controllers.Foo.fooVal}}
and so on, every combination I could think of but it didn't work. Is it possible (and how) to get this running? Can someone please enlighten me?
And by the way: Even on the controllers I use needs successfully, if I debug them (logging them into the console, from my code directly or with a handlebars helper) the controllers property is always undefined. Is there a way to check the needed controller references?
Many thanks in advance.
To my knowledge, Ember's Container looks up stuff via the resolver. And it only looks for stuff on the application's namespace.
Some examples from the DefaultResolver docs.
'controller:post' //=> App.PostController
'controller:posts.index' //=> App.PostsIndexController
'controller:blog/post' //=> Blog.PostController
'controller:basic' //=> Ember.Controller
To achieve what you need you will need to provide a custom Resolver that looks up stuff in the different namespace when creating the Application.
App = Ember.Application.create({
resolver: MyNewResolver
});
For everyone who is interested in how I solved the issue and what I tried and learned:
I did some diggin in the code and tried a few things. I got the desired output using
a) A custom Handlebars helper that returns the property of the controller like this:
{{ myhelper 'App.ModuleName.FooController' 'fooVal'}}
with the following (quick and dirty) helper:
Ember.Handlebars.registerBoundHelper('myhelper', function(arg1, arg2, opts) {
if (opts && opts['data']) {
var ctrl = opts.data.properties[0];
var prop = opts.data.properties[1];
var controller = this.get('container').lookup('controller:' + ctrl.split('.').join('/'));
if (controller) {
return controller.get(prop);
}
}
});
The problem with this is, I couldn't get databinding to work, so if I changed my underlying model, the view didn't update.
b) Overriding the Controllers init() method to get the controller instance like this:
init: function() {
this.module = this.get('container').lookup('controller:App/Module/Foo');
}
and then in the template:
{{module.fooVal}}
In the second way, also Databinding worked, but It didn`t feel correct, so I did some googlin and came across this post on the emberjs issue list:
https://github.com/emberjs/ember.js/issues/683#issuecomment-5122333
As stated by tomdale, nested namespaces are not really something that is encouraged in ember, but multiple 'toplevel' namespaces are ok. So I decided to put up a toplevel namespace for every module and use a custom resolver to resolve them. Works like a charm now and feels like the right way to do it.
Any additional suggestions and comments about the pro's and con's of my second and final way of solving the problem would be much appreciated.

in ember how are view's names determined with respect to the router?

ember rc1. i don't understand how views are automatically instantiated by naming convention wrt their routes.
i have the following resource defined:
this.resource('groups', { path : '/groups' }, function() {
this.resource('received', { path : '/received' }, function() {
this.route('show', { path : '/:asset_link_group_id' });
});
when the router instantiates the view for groups/received/index it looks for a view named ReceivedIndexView. why not GroupsReceivedIndexView ?
the same goes for controllers - it looks for ReceivedIndexController, not GroupsReceivedIndexController. why?
"Routes nested under a resource take the name of the resource plus their name as their route name", from http://emberjs.com/guides/routing/defining-your-routes/
My understanding of the setup is that a route is looked at and then it's parent resource in order to automatically derive the patching. In this way /resource1/sameresourcename/new and /resource2/sameresourcename/new will actually cause problems because it doesn't use the full "tree" to generate these paths/names.
I spent a lot of time researching this as i was having problems understanding the hows and whys of the naming conventions. This is the most informative site I have found in regards to which pieces of the route/resources are picked to create the view/controller/resource name.
From Peter "We intentionally only nest one level deep. The correct solution is what #jamesarosen suggested."
https://github.com/emberjs/ember.js/issues/2086