Search Results

Search found 156 results on 7 pages for 'idiomatic'.

Page 5/7 | < Previous Page | 1 2 3 4 5 6 7  | Next Page >

  • Ruby Multithreading: making one thread wait for a signal from another

    - by Peter
    In Ruby, I want to have two threads running at the same time, and want the background thread to periodically signal the foreground thread. How do I get the foreground thread to block until the background thread says 'go'? I can think of a few ways to do it, but am after the most appropriate, idiomatic Ruby method. In code: loop do # background, thread 1 sleep 3 receive_input # tell foreground input is ready # <-- how do I do this? end and loop do # foreground, thread 2 wait_for_signal_from_background # <-- how do I do this? do_something end

    Read the article

  • Dynamic scoping in Clojure?

    - by j-g-faustus
    Hi, I'm looking for an idiomatic way to get dynamically scoped variables in Clojure (or a similar effect) for use in templates and such. Here is an example problem using a lookup table to translate tag attributes from some non-HTML format to HTML, where the table needs access to a set of variables supplied from elsewhere: (def *attr-table* ; Key: [attr-key tag-name] or [boolean-function] ; Value: [attr-key attr-value] (empty array to ignore) ; Context: Variables "tagname", "akey", "aval" '( ; translate :LINK attribute in <a> to :href [:LINK "a"] [:href aval] ; translate :LINK attribute in <img> to :src [:LINK "img"] [:src aval] ; throw exception if :LINK attribute in any other tag [:LINK] (throw (RuntimeException. (str "No match for " tagname))) ; ... more rules ; ignore string keys, used for internal bookkeeping [(string? akey)] [] )) ; ignore I want to be able to evaluate the rules (left hand side) as well as the result (right hand side), and need some way to put the variables in scope at the location where the table is evaluated. I also want to keep the lookup and evaluation logic independent of any particular table or set of variables. I suppose there are similar issues involved in templates (for example for dynamic HTML), where you don't want to rewrite the template processing logic every time someone puts a new variable in a template. Here is one approach using global variables and bindings. I have included some logic for the table lookup: ;; Generic code, works with any table on the same format. (defn rule-match? [rule-val test-val] "true if a single rule matches a single argument value" (cond (not (coll? rule-val)) (= rule-val test-val) ; plain value (list? rule-val) (eval rule-val) ; function call :else false )) (defn rule-lookup [test-val rule-table] "looks up rule match for test-val. Returns result or nil." (loop [rules (partition 2 rule-table)] (when-not (empty? rules) (let [[select result] (first rules)] (if (every? #(boolean %) (map rule-match? select test-val)) (eval result) ; evaluate and return result (recur (rest rules)) ))))) ;; Code specific to *attr-table* (def tagname) ; need these globals for the binding in html-attr (def akey) (def aval) (defn html-attr [tagname h-attr] "converts to html attributes" (apply hash-map (flatten (map (fn [[k v :as kv]] (binding [tagname tagname akey k aval v] (or (rule-lookup [k tagname] *attr-table*) kv))) h-attr )))) (defn test-attr [] "test conversion" (prn "a" (html-attr "a" {:LINK "www.google.com" "internal" 42 :title "A link" })) (prn "img" (html-attr "img" {:LINK "logo.png" }))) user=> (test-attr) "a" {:href "www.google.com", :title "A link"} "img" {:src "logo.png"} This is nice in that the lookup logic is independent of the table, so it can be reused with other tables and different variables. (Plus of course that the general table approach is about a quarter of the size of the code I had when I did the translations "by hand" in a giant cond.) It is not so nice in that I need to declare every variable as a global for the binding to work. Here is another approach using a "semi-macro", a function with a syntax-quoted return value, that doesn't need globals: (defn attr-table [tagname akey aval] `( [:LINK "a"] [:href ~aval] [:LINK "img"] [:src ~aval] [:LINK] (throw (RuntimeException. (str "No match for " tagname))) ; ... more rules [(string? ~akey)] [] ))) Only a couple of changes are needed to the rest of the code: In rule-match?, when syntax-quoted the function call is no longer a list: - (list? rule-val) (eval rule-val) + (seq? rule-val) (eval rule-val) In html-attr: - (binding [tagname tagname akey k aval v] - (or (rule-lookup [k tagname] *attr-table*) kv))) + (or (rule-lookup [k tagname] (attr-table tagname k v)) kv))) And we get the same result without globals. (And without dynamic scoping.) Are there other alternatives to pass along sets of variable bindings declared elsewhere, without the globals required by Clojure's binding? Is there an idiomatic way of doing it, like Ruby's binding or Javascript's function.apply(context)?

    Read the article

  • Why the "mutable default argument fix" syntax is so ugly, asks python newbie

    - by Cawas
    Now following my series of "python newbie questions" and based on another question. Go to http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables and scroll down to "Default Parameter Values". There you can find the following: def bad_append(new_item, a_list=[]): a_list.append(new_item) return a_list def good_append(new_item, a_list=None): if a_list is None: a_list = [] a_list.append(new_item) return a_list So, question here is: why is the "good" syntax over a known issue ugly like that in a programming language that promotes "elegant syntax" and "easy-to-use"? Why not just something in the definition itself, that the "argument" name is attached to a "localized" mutable object like: def better_append(new_item, a_list=[].local): a_list.append(new_item) return a_list I'm sure there would be a better way to do this syntax, but I'm also almost positive there's a good reason to why it hasn't been done. So, anyone happens to know why?

    Read the article

  • How to check function parameters in Go

    - by deamon
    Guava Preconditions allows to check method parameters in Java easily. public void doUsefulThings(Something s, int x, int position) { checkNotNull(s); checkArgument(x >= 0, "Argument was %s but expected nonnegative", x); checkElementIndex(position, someList.size()); // ... } These check methods raise exceptions if the conditions are not met. Go has no exceptions but indicates errors with return values. So I wonder how an idiomatic Go version of the above code would look like.

    Read the article

  • more ruby way of gsub from array

    - by aharon
    My goal is to let there be x so that x("? world. what ? you say...", ['hello', 'do']) returns "hello world. what do you say...". I have something that works, but seems far from the "Ruby way": def x(str, arr, rep='?') i = 0 query.gsub(rep) { i+=1; arr[i-1] } end Is there a more idiomatic way of doing this? (Let me note that speed is the most important factor, of course.)

    Read the article

  • Is there an equivalent for the Zip function in Clojure Core or Contrib?

    - by John Kane
    In Clojure, I want to combine two lists to give a list of pairs, > (zip '(1 2 3) '(4 5 6)) ((1 4) (2 5) (3 6)) In Haskell or Ruby the function is called zip. Implementing it is not difficult, but I wanted to make sure I wasn't missing a function in Core or Contrib. There is a zip namespace in Core, but it is described as providing access to the Zipper functional technique, which does not appear to be what I am after. Is there an equivalent function for combining 2 or more lists, in this way, in Core? If there is not, is it because there is an idiomatic approach that renders the function unneeded?

    Read the article

  • Determine if PowerShell function is running as part of a pipeline?

    - by Richard Cook
    Can a PowerShell function determine if it is being run as part of a pipeline? I have a function which populates an array with instances of FileInfo which I would like to "yield" to the pipeline if the function is being run this way or produce some pretty output if the function is being invoked by itself from the command line. function Do-Something { $file_infos = @() # Populate $file_infos with FileInfo instances... if (INVOKED_IN_PIPELINE) { return $file_infos } else { foreach ($file_info in $file_infos) { write-host -foregroundcolor yellow $file_info.fullname } } } Basically, I'm trying to figure out how to implement INVOKED_IN_PIPELINE. If it is run in a pipeline (e.g. Do-Something | format-table fullname), I would simply yield the array, but if run directly (e.g. Do-Something), it would simply pretty-print the output. Is there a way to do this? If there is a more "idiomatic" way to achieve this kind of thing, I would also be interested to know.

    Read the article

  • How does one reduce a list of boolean values in Common Lisp?

    - by postfuturist
    Given a list of values, I want to reduce the list to T if all the elements are not NIL, NIL if not. This gives me an error: (apply #'and (get-some-list)) As does this: (reduce #'and (get-some-list)) This is the best I've come up with: [11]> (defun my-and (x y) (and x y)) MY-AND [12]> (reduce #'my-and '(T T T T T)) T [13]> (reduce #'my-and '(T T T T NIL)) NIL Why is "#'and" invalid? Is there a more idiomatic way to do this in Common Lisp?

    Read the article

  • Filtering subsets using Linq

    - by Nathan Matthews
    Hi All, Imagine a have a very long enunumeration, too big to reasonably convert to a list. Imagine also that I want to remove duplicates from the list. Lastly imagine that I know that only a small subset of the initial enumeration could possibly contain duplicates. The last point makes the problem practical. Basically I want to filter out the list based on some predicate and only call Distinct() on that subset, but also recombine with the enumeration where the predicate returned false. Can anyone think of a good idiomatic Linq way of doing this? I suppose the question boils down to the following: With Linq how can you perform selective processing on a predicated enumeration and recombine the result stream with the rejected cases from the predicate?

    Read the article

  • reading a line, tokenizing and assigning to struct in C

    - by Dervin Thunk
    line is fgets'd, and running in a while loop with counter n, d is a struct with 2 char arrays, p and q. Basically, in a few words, I want to read a line, separate it into 2 strings, one up until the first space, and the rest of the line. I clean up afterwards (\n from the file becomes \'0'). The code works, but is there a more idiomatic way to do this? What errors am I running into "unknowingly"? int spc = strcspn(line," "); strncpy(d[n].p, line, spc); d[n].p[spc+1]='\0'; int l = strlen(line)-spc; strncpy(d[n].q, line+spc+1, l); char* nl = strchr(d[n].q, '\n'); if(nl){ *nl='\0'; } n++; Thanks.

    Read the article

  • What is the pythonic way to add type information to an object's attributes?

    - by Tikitu
    I'm building classes where I know the types of the attributes, but Python of course doesn't. While it's un-pythonic to want to tell it, supposing I do want to, is there an idiomatic way to do so? Why: I'm reading in serialised data (without type information) involving objects-nested-inside-objects. It's easy to put it into nested dictionaries, but I want it in objects of my class-types, to get the right behaviours as well as the data. For instance: suppose my class Book has an attribute isbn which I will fill with an ISBNumber object. My serialised data gives me the isbn as a string; I would like to be able to look at Book and say "That field should be filled by ISBNumber(theString)." Bonus glee for me if the solution can be applied to classes I get from someone else without editing their code.

    Read the article

  • What is the most efficient functional version of the following imperative code?

    - by justin.r.s.
    I'm learning Scala and I want to know the best way of expressing this imperative pattern using Scala's functional programming capabilities. def f(l: List[Int]): Boolean = { for (e <- l) { if (test(e)) return true } } return false } The best I can come up with is along the lines of: l map { e => test(e) } contains true But this is less efficient since it calls test() on each element, whereas the imperative version stops on the first element that satisfies test(). Is there a more idiomatic functional programming technique I can use to the same effect? The imperative version seems awkward in Scala.

    Read the article

  • better for-loop syntax for detecting empty sequences?

    - by Dmitry Beransky
    Hi, Is there a better way to write the following: row_counter = 0 for item in iterable_sequence: # do stuff with the item counter += 1 if not row_counter: # handle the empty-sequence-case Please keep in mind that I can't use len(iterable_sequence) because 1) not all sequences have known lengths; 2) in some cases calling len() may trigger loading of the sequence's items into memory (as the case would be with sql query results). The reason I ask is that I'm simply curious if there is a way to make above more concise and idiomatic. What I'm looking for is along the lines of: for item in sequence: #process item *else*: #handle the empty sequence case (assuming "else" here worked only on empty sequences, which I know it doesn't)

    Read the article

  • How to change password hashing algorithm when using spring security?

    - by harry
    I'm working on a legacy Spring MVC based web Application which is using a - by current standards - inappropriate hashing algorithm. Now I want to gradually migrate all hashes to bcrypt. My high level strategy is: New hashes are generated with bcrypt by default When a user successfully logs in and has still a legacy hash, the app replaces the old hash with a new bcrypt hash. What is the most idiomatic way of implementing this strategy with Spring Security? Should I use a custom Filter or my on AccessDecisionManager or …?

    Read the article

  • How would you write this Clojure snippet in Ruby and/or Haskell?

    - by dnolen
    I was working on a Rails template and was trying to write a bit of code that allows me to populate a table or multiple columns of ul tags "top-to-bottom" and "left-to-right" across however many columns I specify. I'm just getting the hang of Ruby so I couldn't figure this out. I'm also curious about an idiomatic Haskell version for this useful snippet. Improvements to Clojure version appreciated: (defn table [xs & {:keys [cols direction] :or {cols 1 direction 'right}}] (into [] (condp = direction 'down (let [c (count xs) q (int (/ c cols)) n (if (> (mod c q) 0) (inc q) q)] (apply map vector (partition n n (repeat nil) xs))) 'right (map vec (partition cols cols (repeat nil) xs))))) With this bit of code I can then do the following: (table (range 10) :cols 3) Printed out this would look like so: 0 1 2 3 4 5 6 7 8 9 And the trickier one: (table (range 10) :cols 3 :direction 'down) Looks like so: 0 4 8 1 5 9 2 6 3 7

    Read the article

  • F# - Function with no arguments?

    - by Rubys
    When thinking in a functional mindset, given that functions are supposed to be pure, one can conclude any function with no arguments is basically just a value. However, reallity gets in the way, and with different inputs, I might not need a certain function, and if that function is computationally expensive, I'd like to not evaluate it if it's not needed. I found a workaround, using let func _ = ... and calling it with func 1 or whatever, but that feels very non-idiomatic and confusing to the reader. This boils down to one question: In F#, Is there a proper way to declare a function with zero arguments, without having it evaluated on declaration?

    Read the article

  • How to check whether a String fully matches a Regex in Scala?

    - by mkneissl
    Assume I have a Regex pattern I want to match many Strings to. val Digit = """\d""".r I just want to check whether a given String fully matches the Regex. What is a good and idiomatic way to do this in Scala? I know that I can pattern match on Regexes, but this is syntactically not very pleasing in this case, because I have no groups to extract: scala> "5" match { case Digit() => true case _ => false } res4: Boolean = true Or I could fall back to the underlying Java pattern: scala> Digit.pattern.matcher("5").matches res6: Boolean = true which is not elegant, either. Is there a better solution?

    Read the article

  • Why does coffeescript generate classes like this?

    - by ryeguy
    Given the following coffeescript code: class Animal constructor: (@name) -> speak: (things) -> "My name is #{@name} and I like #{things}" This is generated: var Animal = (function() { function Animal(name) { this.name = name; } Animal.prototype.speak = function(things) { return "My name is " + this.name + " and I like " + things; }; return Animal; })(); But why isn't this more idiomatic code generated? var Animal = function Animal(name) { this.name = name; }; Animal.prototype.speak = function(things) { return "My name is " + this.name + " and I like " + things; }; I know that coffeescript wraps a lot of stuff in anonymous functions to control scope leak, but what could leak here?

    Read the article

  • Trimming strings in Go

    - by user1263980
    I'm trying to read an entire line from the console (including whitespace), then process it. Using bufio.ReadString, the newline character is read together with the input, so I came up with the following code to trim the newline character: input,_:=src.ReadString('\n') inputFmt:=input[0:len(input)-2]+"" Is there a more idiomatic way to do this? That is, is there already a library that takes care of the ending null byte when extracting substrings for you? (Yes, I know there is already a way to read a line without the newline character in go readline -> string but I'm looking more for elegant string manipulation.)

    Read the article

  • Why is Java the lingua franca at so many institutions?

    - by Billy ONeal
    EDIT: This question at first seems to be bashing Java, and I guess at this point it is a bit. However, the bigger point I am trying to make is why any one single language is chosen as the one end all be all solution to all problems. Java happens to be the one that's used so that's the one I had to beat on here, but I'm not intentionality ripping Java a new one :) I don't like Java in most academic settings. I'm not saying the language itself is bad -- it has several extremely desirable aspects, most importantly the ability to run without recompilation on most any platform. Nothing wrong with using the language for Your Next App ^TM. (Not something I would personally do, but that's more because I have less experience with it, rather than it's design being poor) I think it is a waste that high level CS courses are taught using Java as a language. Too many of my co-students cannot program worth a damn, because they don't know how to work in a non-garbage-collected world. They don't fundamentally understand the machines they are programming for. When someone can work outside of a garbage collected world, they can work inside of one, but not vice versa. GC is a tool, not a crutch. But the way it is used to teach computer science students is a as a crutch. Computer science should not teach an entire suite of courses tailored to a single language. Students leave with the idea that all good design is idiomatic Java design, and that Object Oriented Design is the ONE TRUE WAY THAT IS THE ONLY WAY THINGS CAN BE DONE. Other languages, at least one of them not being a garbage collected language, should be used in teaching, in order to give the graduate a better understanding of the machines. It is an embarrassment that somebody with a PHD in CS from a respected institution cannot program their way out of a paper bag. What's worse, is that when I talk to those CS professors who actually do understand how things operate, they share feelings like this, that we're doing a disservice to our students by doing everything in Java. (Note that the above would be the same if I replaced it with any other language, generally using a single language is the problem, not Java itself) In total, I feel I can no longer respect any kind of degree at all -- when I can't see those around me able to program their way out of fizzbuzz problems. Why/how did it get to be this way?

    Read the article

  • Surviving MATLAB and R as a Hardcore Programmer

    - by dsimcha
    I love programming in languages that seem geared towards hardcore programmers. (My favorites are Python and D.) MATLAB is geared towards engineers and R is geared towards statisticians, and it seems like these languages were designed by people who aren't hardcore programmers and don't think like hardcore programmers. I always find them somewhat awkward to use, and to some extent I can't put my finger on why. Here are some issues I have managed to identify: (Both): The extreme emphasis on vectors and matrices to the extent that there are no true primitives. (Both): The difficulty of basic string manipulation. (Both): Lack of or awkwardness in support for basic data structures like hash tables and "real", i.e. type-parametric and nestable, arrays. (Both): They're really, really slow even by interpreted language standards, unless you bend over backwards to vectorize your code. (Both): They seem to not be designed to interact with the outside world. For example, both are fairly bulky programs that take a while to launch and seem to not be designed to make simple text filter programs easy to write. Furthermore, the lack of good string processing makes file I/O in anything but very standard forms near impossible. (Both): Object orientation seems to have a very bolted-on feel. Yes, you can do it, but it doesn't feel much more idiomatic than OO in C. (Both): No obvious, simple way to get a reference type. No pointers or class references. For example, I have no idea how you roll your own linked list in either of these languages. (MATLAB): You can't put multiple top level functions in a single file, encouraging very long functions and cut-and-paste coding. (MATLAB): Integers apparently don't exist as a first class type. (R): The basic builtin data structures seem way too high level and poorly documented, and never seem to do quite what I expect given my experience with similar but lower level data structures. (R): The documentation is spread all over the place and virtually impossible to browse or search. Even D, which is often knocked for bad documentation and is still fairly alpha-ish, is substantially better as far as I can tell. (R): At least as far as I'm aware, there's no good IDE for it. Again, even D, a fairly alpha-ish language with a small community, does better. In general, I also feel like MATLAB and R could be easily replaced by plain old libraries in more general-purpose langauges, if sufficiently comprehensive libraries existed. This is especially true in newer general purpose languages that include lots of features for library writers. Why do R and MATLAB seem so weird to me? Are there any other major issues that you've noticed that may make these languages come off as strange to hardcore programmers? When their use is necessary, what are some good survival tips? Edit: I'm seeing one issue from some of the answers I've gotten. I have a strong personal preference, when I analyze data, to have one script that incorporates the whole pipeline. This implies that a general purpose language needs to be used. I hate having to write a script to "clean up" the data and spit it out, then another to read it back in a completely different environment, etc. I find the friction of using MATLAB/R for some of my work and a completely different language with a completely different address space and way of thinking for the rest to be a huge source of friction. Furthermore, I know there are glue layers that exist, but they always seem to be horribly complicated and a source of friction.

    Read the article

  • Educational, well-written FOSS projects to read, study or discuss

    - by Godot
    Before you say it: yes, this "question" has been asked other times. However, I could not fine many of such questions and not that easily, and those I found had similar results. What I'm trying to say that there are no comprehensive lists of well written Open Source projects, so I decided to set some requirements for the entries (one or possibly more): Idiomatic use of the language in which they are written The project should be lightweight. Not as in "a few kbs", as in "clean" and possibly following the UNIX philosophy, making an efficient use of resources and performing its duty and nothing more. No code bloat, most importantly. Projects like Firefox and GNOME wouldn't qualify, for example. Minimal reliance on external, non-standard libraries, with exceptions for some common FOSS libraries (curses, Xlib, OpenGL and possibly "usual suspects" like gtk+, webkit and Boost). Reliance on well-written libraries is welcome. No reliance on proprietary software - for obvious reasons (programs that rely on XNA, DirectX, Cocoa and similar, for example). Well-documented code is welcome. Include link to web interfaces to their repositories if possible. Here are some sample projects that often pop up in these threads: Operating Systems Plan 9 from Bell Labs: More or less, the official "sequel" to UNIX. Written in C by the same people who invented C! NetBSD: The most portable BSD implementation, written in C and also a good example of portable and organized code. Network and Databases Sqlite: Extremely lightweight and extremely efficient, one of the best pieces of C software I've seen. Count the lines yourself! Lighttpd: A small but pretty reliable web server written in C. Programming languages and VMs Lua: extremely lightweight multi-paradigm programming language. Written in C. Tiny C Compiler: Really tiny C compiler. Not really comparable to GCC or Clang but does its job. PyPy: A Python implementation written in Python. Pharo: OK, I admit it, I'm not really a Smalltalk expert but Pharo is a fork of Squeak and looked rather interesting. Stackless Python - An implementation of Python that doesn't rely on the C call stack - written in C (with some parts in Python) Games and 3D: Angband: One of the most accessible roguelike codebases around here, written in C. Ogre3D: Cross-platform 3D engine. Gets bloated if you don't skip the platform-specific implementation code, otherwise is a pretty solid example of good C++ OO. Simon Tatham's Portable Puzzle Collection: Title says it all. Other - dwm: Lightweight window manager. Written in C. Emulation and Reverse Engineering - Bochs: x86 emulator, written in C++ and tiny enough. - MAME: If you want to see C at one of its lowest levels, MAME is for you. May not be as clean as the other projects but it can teach you A LOT. Before you ask: I didn't mention Linux because it has become quite bloated in the last few years, Linus has also confirmed it. Nonetheless, it'd be a great educational read the same, even if for other reasons. Same for GCC. Feel free to edit or wikify my post. I hope you won't lock my question, I'm only trying to organize a little community effort for the good of all those people who want to enhance their coding skills.

    Read the article

  • Suggestions for doing async I/O with Task Parallel Library

    - by anelson
    I have some high performance file transfer code which I wrote in C# using the Async Programming Model (APM) idiom (eg, BeginRead/EndRead). This code reads a file from a local disk and writes it to a socket. For best performance on modern hardware, it's important to keep more than one outstanding I/O operation in flight whenever possible. Thus, I post several BeginRead operations on the file, then when one completes, I call a BeginSend on the socket, and when that completes I do another BeginRead on the file. The details are a bit more complicated than that but at the high level that's the idea. I've got the APM-based code working, but it's very hard to follow and probably has subtle concurrency bugs. I'd love to use TPL for this instead. I figured Task.Factory.FromAsync would just about do it, but there's a catch. All of the I/O samples I've seen (most particularly the StreamExtensions class in the Parallel Extensions Extras) assume one read followed by one write. This won't perform the way I need. I can't use something simple like Parallel.ForEach or the Extras extension Task.Factory.Iterate because the async I/O tasks don't spend much time on a worker thread, so Parallel just starts up another task, resulting in potentially dozens or hundreds of pending I/O operations; way too much! You can work around that by Waiting on your tasks, but that causes creation of an event handle (a kernel object), and a blocking wait on a task wait handle, which ties up a worker thread. My APM-based implementation avoids both of those things. I've been playing around with different ways to keep multiple read/write operations in flight, and I've managed to do so using continuations that call a method that creates another task, but it feels awkward, and definitely doesn't feel like idiomatic TPL. Has anyone else grappled with an issue like this with the TPL? Any suggestions?

    Read the article

  • How to Global onRouteRequest directly to onBadRequest?

    - by virtualeyes
    EDIT Came up with this to sanitize URI date params prior to passing off to Play router val ymdMatcher = "\\d{8}".r // matcher for yyyyMMdd URI param val ymdFormat = org.joda.time.format.DateTimeFormat.forPattern("yyyyMMdd") def ymd2Date(ymd: String) = ymdFormat.parseDateTime(ymd) override def onRouteRequest(r: RequestHeader): Option[Handler] = { import play.api.i18n.Messages ymdMatcher.findFirstIn(r.uri) map{ ymd=> try { ymd2Date( ymd); super.onRouteRequest(r) } catch { case e:Exception => // kick to "bad" action handler on invalid date Some(controllers.Application.bad(Messages("bad.date.format"))) } } getOrElse(super.onRouteRequest(r)) } ORIGINAL Let's say I want to return a BadRequest result type for all /foo URIs: override def onBadRequest(r: RequestHeader, error: String) = { BadRequest("Bad Request: " + error) } override def onRouteRequest(r: RequestHeader): Option[Handler] = { if(r.uri.startsWith("/foo") onBadRequest("go away") else super.onRouteRequest(r) } Of course does not work, since the expected return type is Option[play.api.mvc.Handler] What's the idiomatic way to deal with this, create a default Application controller method to handle filtered bad requests? Ideally, since I know in onRouteRequest that /foo is in fact a BadRequest, I'd like to call onBadRequest directly. Should note that this is a contrived example, am actually verifying a URI yyyyMMdd date param, and BadRequest-ing if it does not parse to a JodaTime instance -- basically a catch-all filter to sanitize a given date param rather than handling on every single controller method call, not to mention, avoiding cluttering up application log with useless stack traces re: invalid date parse conversions (have several MBs of these junk trace entries accruing daily due to users pointlessly manipulating the uri date in attempts to get at paid subscriber content)

    Read the article

  • Ruby - Immutable Objects

    - by Chris Bunch
    I've got a highly multithreaded app written in Ruby that shares a few instance variables. Writes to these variables are rare (1%) while reads are very common (99%). What is the best way (either in your opinion or in the idiomatic Ruby fashion) to ensure that these threads always see the most up-to-date values involved? Here's some ideas so far that I had (although I'd like your input before I overhaul this): Have a lock that most be used before reading or writing any of these variables (from Java Concurrency in Practice). The downside of this is that it puts a lot of synchronize blocks in my code and I don't see an easy way to avoid it. Use Ruby's freeze method (see here), although it looks equally cumbersome and doesn't give me any of the synchronization benefits that the first option gives. These options both seem pretty similar but hopefully anyone out there will have a better idea (or can argue well for one of these ideas). I'd also be fine with making the objects immutable so they aren't corrupted or altered in the middle of an operation, but I don't know Ruby well enough to make the call on my own and this question seems to argue that objects are highly mutable.

    Read the article

< Previous Page | 1 2 3 4 5 6 7  | Next Page >