Consider a model Post which has a title, description and a locale_restrictions field.
The locale restrictions field specifies in which locales the post should be displayed. It contains a CSV value: en,de,be,nl.
What I would like to do is use either a default_scope or a named scope to only return the model instances for a specific locale. Something like (with a localized scope): Post.localized.all. This scope then looks at the current locale I18n.locale and returns the posts that have that locale in their locale_restrictions CSV.
I cannot seem to get this working, having tried quite a couple of options. The closest I came was with a SQL LIKE expression:
default_scope -> { where("locale_restrictions LIKE (?)", "%#{I18n.locale.to_s}%") }
However, this fails when there's, for example, both a :en and :benl locale, since %en% will match :benl.
Apparently you can't get access to self.locale_restrictions within a scope. self returns the class instead of the instance. I can't figure out a way to split the locale_restrictions and check them.
What would be the best way to go about this using scopes, or are there any best practices regarding localizing database that I'm missing out on?
I'm basically looking for an easy way to scope my controller instance variables to a specific locale. Any help would be greatly appreciated.
Instead of using LIKE you can use REGEXP and include beginning-of-word and end-of-word boundries in the regular expression. This should do the trick:
default_scope -> { where("locale_restrictions REGEXP (?)", "[[:<:]]#{I18n.locale.to_s}[[:>:]]") }
Related
While working on log Queries in an arm template, I stuck with how to pass parameter values or variable values in the log Query.
parameters:
{
"resProviderName":
{
"value": "Microsoft.Storage"
}
}
For Eg:
AzureMetrics | where ResourceProvider == **parameters('resProviderName')** | where Resource == 'testacc'
Here I am facing an error like, it was taking parameters('resProviderName') as a value and it was not reading value from that particular parameter "resProviderName" and my requirement is to take the values from parameters or variables and should not hardcode like what I did in the above query as Resource=='testacc'.
Do we have any option to read the values from either parameters or variables in the log query?
If so, please help on this issue.
The answer to this would depend on what this query segment is a part of, and how your template is structured.
It appears that you're trying to reference a resource in the query. It is best to use one of the many available template resource functions if you want the details of the resource like its resourceID (within the resources section). When referencing a resource that is deployed in the same template, provide the name of the resource through a parameter. When referencing a resource that isn't deployed in the same template, fetch the resource ID.
Also, I'd recommend referring to the ARM snippet given this example to understand how queries can be constructed as custom variables as opposed to the other way round. According to ARM template best practices, variables should be used for values that you need to use more than once in a template. If a value is used only once, a hard-coded value makes your template easier to read. For more info, please take a look at this doc.
Hope this helps.
This is an old question but I bumped into this while searching for the same issue.
I'm much more familiar with Bicep templates so what I did to figure out was to create a Bicep template, construct the query by using the variables and compile it. This will generate a ARM template and you can analyze it.
I figured out you can use both concat or format functions in order to construct your query using variables.
I preferred the format one since it looks more elegant and readable (also, Bicep build generates the string using the format function).
So based on this example, the query would be something like this:
query: "[format('AzureMetrics | where ResourceProvider == {0} | where Resource == ''testacc'' ', parameters('resProviderName') )]"
Don't forget to escape the ' in the ARM template which you do by doubling the single quote.
I hope this helps some people.
André
I need to retrieve the collections to which a given document belongs in Marklogic.
I know xdmp command does that. But I need to use it in cts query to retrieve the data and then filter records from it.
xdmp:document-get-collections("uri of document") can't be run inside cts-query to give appropriate data.
Any idea how can it be done using cts query?
Thanks
A few options come to mind:
Option One: Use cts:values()
cts:values(cts:collection-reference())
If you check out the documentation, you will see that you can also restrict this to certain fragments by passing a query as one of the parameters.
**Update: [11-10-2017]
The comment attached to this asked for a sample of restricting the results of cts:values() to a single document(for practical purposes, I will say fragment == document)
The documentation for cts:values explains this. It is the 4th parameter - a query to restrict the results. Get to know this pattern as it is part of many features of MarkLogic. It is your friend. The query I would use for this problem statement would be a cts:document-query();
An Example:
cts:values(
cts:collection-reference(),
(),
(),
cts:document-query('/path/to/my/document')
)
Full Example:
cts:search(
collection(),
cts:collection-query(
cts:values(
cts:collection-reference(),
(),
(),
cts:document-query('/path/to/my/document')
)
)
)[1 to 10]
Option two: use cts:collection-match()
Need more control over returning just some of the collections from a document, then use cts:colection-match(). Like the first option, you can restrict the results to just some fragments. However, it has the benefit of having an option for a pattern.
Attention:
They both return a sequence - perfect for feeding into other parts of your query. However, under the hood, I believe they work differently. The second option is run against a lexicon. The larger the list of unique collection names and the more complex your pattern match, the longer for resolution. I use collection-match in projects. However, I usually use it when I can limit the possible choices by restricting the results to a smaller number of documents.
You can't do this in a single step. You have to run code first to retrieve collections associated with a document. You can use something like xdmp:document-get-collections for that. You then have to feed that into a cts query that you build dynamically:
let $doc-collections := xdmp:document-get-collections($doc-uri)
return
cts:search(collection(), cts:collection-query($doc-collections))[1 to 10]
HTH!
Are you looking for cts:collection-query()?
Insert two XML files to the same collection:
xquery version "1.0-ml";
xdmp:document-insert("/a.xml", <root><sub1><a>aaa</a></sub1></root>,
map:map() => map:with("collections", ("coll1")));
xdmp:document-insert("/b.xml", <root><sub2><a>aaa</a></sub2></root>,
map:map() => map:with("collections", ("coll1")));
Search the collection:
xquery version "1.0-ml";
let $myColl:= xdmp:document-get-collections("/a.xml")
return
cts:search(/root,
cts:and-query((cts:collection-query($myColl),cts:element-query(xs:QName("a"),"aaa")
)))
How do I make PhpStorm suggest input variables ?
In Java/C# and the like (with VS/Eclipse), when I have a function that receives enum-input-variable, like:
void func(SomeEnum var);
Whenever I type func(, the editor kindly suggests all the available enums (of type SomeEnum). I look for this same functionality in PHP, when I have a predefined set of input options (like DB's tables).
Maybe with the use of Intellilang or these # tags (PHPDocs ?) I can predefine such list ?
Currently you cannot limit the possible options for code completion in this regard: PHP simply has no such "thing" similar to Enum. The only limitation you can do is limit by expected parameter type (e.g. int variable will not be offered when parameter expects an array).
I think this will be the correct ticket to look for: http://youtrack.jetbrains.com/issue/WI-854 and maybe http://youtrack.jetbrains.com/issue/WI-3623
Kind of related (for array indexes completion): http://youtrack.jetbrains.com/issue/WI-3423
I'm writing a web application (in Python, not that it matters). One of the features is that people can leave comments on things. I have a class for comments, basically like so:
class Comment:
user = ...
# other stuff
where user is an instance of another class,
class User:
name = ...
# other stuff
And of course in my template, I have
<div>${comment.user.name}</div>
Problem: Let's say I allow people to post comments anonymously. In that case comment.user is None (undefined), and of course accessing comment.user.name is going to raise an error. What's the best way to deal with that? I see three possibilities:
Use a conditional in the template to test for that case and display something different. This is the most versatile solution, since I can change the way anonymous comments are displayed to, say, "Posted anonymously" (instead of "Posted by ..."), but I've often been told that templates should be mindless display machines and not include logic like that. Also, other people might wind up writing alternate templates for the same application, and I feel like I should be making things as easy as possible for the template writer.
Implement an accessor method for the user property of a Comment that returns a dummy user object when the real user is undefined. This dummy object would have user.name = 'Anonymous' or something like that and so the template could access it and print its name with no error.
Put an actual record in my database corresponding to a user with user.name = Anonymous (or something like that), and just assign that user to any comment posted when nobody's logged in. I know I've seen some real-world systems that operate this way. (phpBB?)
Is there a prevailing wisdom among people who write these sorts of systems about which of these (or some other solution) is the best? Any pitfalls I should watch out for if I go one way vs. another? Whoever gives the best explanation gets the checkmark.
I'd go with the first option, using an if switch in the template.
Consider the case of localization: You'll possibly have different templates for each language. You can easily localize the "anonymous" case in the template itself.
Also, the data model should have nothing to do with the output side. What would you do in the rest of the code if you wanted to test whether a user has a name or not? Check for == 'Anonymous' each time?
The template should indeed only be concerned with outputting data, but that doesn't mean it has to consist solely of output statements. You usually have some sort of if user is logged in, display "Logout", otherwise display "Register" and "Login" case in the templates. It's almost impossible to avoid these.
Personally, I like for clean code, and agree that templates should not have major logic. So in my implementations I make sure that all values have "safe" default values, typically a blank string, pointer to a base class or equivalent. That allows for two major improvements to the code, first that you don't have to constantly test for null or missing values, and you can output default values without too much logic in your display templates.
So in your situation, making a default pointer to a base value sounds like the best solution.
Your 3rd option: Create a regular User entity that represents an anonymous user.
I'm not a fan of None for database integrity reasons.
How do you guys avoid keyword conflicts in your language?
For example, I'm creating a class (VB 2008) to hold all the configuration variables for some reports we generate. Naturally, one of the variables is "Date". And of course you can't have anything named the same as a keyword. In VB 2008 you do have the option of surrounding a conflicting word with []'s and fix it but I've always seen that as a hack. Any suggestions? What are your names to get around common keywords?
Code to help visualize...
Dim m_Title As String
Dim m_Date As String
Public Property Title() As String
Get
Return m_Title
End Get
Set(ByVal value As String)
m_Title = value
End Set
End Property
Public Property [Date]() As String
Get
End Get
Set(ByVal value As String)
End Set
End Property
Probably think about more specific nature of the variable?
From your example, the "Date" can be "Created Date" or "Posted Date" or anything else. If you find your variable names too trivial, you may be oversimplifying (or even obfuscating) your code. Help your coworkers by creating a clear but concise variable names.
Don't look at [Date] as a hack; if your property represents a date, it should be called Date. Use the tools you have available to get the job done. Personally I feel that properties that have the names they do only to get around such conflicts are more of a hack, since you will get to deal with it every time you use the property.
misspell your variable names!
On .NET, it is reasonable to consider the Common Language Specification (CLS) as the lowest common denominator that you should cater to. This is documented in ECMA-335 "Common Language
Infrastructure (CLI) Partitions I to VI". Here's what it says specifically about names; a note in CLS Rule #4 (8.5.1 "Valid names"):
CLS (consumer): Need not consume types that violate CLS Rule 4, but shall have a mechanism to allow access to named items that use one of its own keywords as the name.
So no, it's not really a hack, but a definite rule. The reason why it's there is that, as .NET is extensible as far as languages targeting it go, you can never avoid name clashes. If you cover C#, there's VB. If you cover C# and VB, there's C++/CLI. If you cover all those, there's F# and Delphi Prism. And so on. Hence why it is mandated by CLS that languages provide a way to escape their keywords as identifiers; and all languages I've listed provide some way to do so (and thus are compliant CLS consumers).
In general, it is still considered good manners to avoid clashes with either C# or VB non-context keywords, mainly because those two languages are the most popular by a very large margin. For example, it is the reason why it's HashSet and not just Set - the latter is a VB keyword. The full listings are:
C# keywords
VB keywords
Most languages have something to escape any reserved words. C# has # so you can use #class as an argument name (something MVC adopters are learning).
If the domain states that a certain word be used to describe it then that is what the escaping of reserved words is there for. I wouldn't be afraid to escape reserved words to get my model close to the domain even if it means more typing - the clarity is worth it!
To avoid naming conflicts with keywords, I simply don't use keywords.
In your case, Date. Date of what? If I had to maintain your application that would probably be the first thing I'd ask. The great thing about keywords is that they're completely generic, something a variable name should never be.
There is no silver bullet, but modern languages help a lot with better abilities to manage namespaces.
In my case, I curse the fact that C has an 'index' command.
"Date_" or "_Date".
This is one question where Perl dodges the question entirely.
Variables always have one of $%#*&, the only things that can conflict are Globs/Handles, and subroutines.
Even that isn't much of a problem because Globs/Handles aren't used very much any more.
Subroutines and keywords are very much the same in Perl. If you need to get at the built-in subroutine/keyword you can get at it by appending CORE::, for example CORE::dump.
Really I think the only keywords you would have a problem with are sub, my, local, and 'our', because those keywords are parsed very early in parser. Note that you can still create a sub with those names, it just won't work without specifying the full name, or from a blessed reference, or with a symbolic reference.
{
package test;
sub my{ print "'my' called using $_[-1]\n" };
sub new{ bless {}, $_[0] };
sub sub{ print "'sub' called using $_[-1]\n" };
sub symbolic{
*{__PACKAGE__.'::'.$_[1]}{CODE}->('symbolic reference');
}
my $var; # notice this doesn't call test::my()
}
package main;
my $test = test->new;
# Called from a blessed reference
$test->my('blessed reference');
$test->sub('blessed reference');
print "\n";
# Called using the full name
test::my('full name');
test::sub('full name');
print "\n";
# Called using a symbolic reference
$test->symbolic('my');
$test->symbolic('sub');
Output:
'my' called using blessed reference
'sub' called using blessed reference
'my' called using full name
'sub' called using full name
'my' called using symbolic reference
'sub' called using symbolic reference